From 470115ae90bf515385f207aac4bb01428804bfe9 Mon Sep 17 00:00:00 2001 From: lacksfish Date: Mon, 3 Jun 2019 14:11:20 +0200 Subject: [PATCH] Readd C++ Qt5 client and other client improvements --- README.md | 1 + android/.openapi-generator/VERSION | 2 +- .../org/openapitools/client/ApiException.java | 2 +- .../org/openapitools/client/ApiInvoker.java | 2 +- .../org/openapitools/client/JsonUtil.java | 2 +- .../java/org/openapitools/client/Pair.java | 2 +- .../client/api/AccountManagementApi.java | 2 +- .../client/api/AuthenticationApi.java | 2 +- .../openapitools/client/api/InternalApi.java | 2 +- .../client/api/MarketDataApi.java | 2 +- .../openapitools/client/api/PrivateApi.java | 2 +- .../openapitools/client/api/PublicApi.java | 2 +- .../client/api/SupportingApi.java | 2 +- .../openapitools/client/api/TradingApi.java | 2 +- .../openapitools/client/api/WalletApi.java | 2 +- .../openapitools/client/auth/ApiKeyAuth.java | 2 +- .../client/auth/Authentication.java | 2 +- .../client/auth/HttpBasicAuth.java | 2 +- .../client/model/AddressBookItem.java | 2 +- .../client/model/BookSummary.java | 2 +- .../openapitools/client/model/Currency.java | 2 +- .../client/model/CurrencyPortfolio.java | 2 +- .../model/CurrencyWithdrawalPriorities.java | 2 +- .../openapitools/client/model/Deposit.java | 2 +- .../openapitools/client/model/Instrument.java | 2 +- .../client/model/KeyNumberPair.java | 2 +- .../org/openapitools/client/model/Order.java | 2 +- .../model/OrderIdInitialMarginPair.java | 2 +- .../openapitools/client/model/Portfolio.java | 2 +- .../client/model/PortfolioEth.java | 2 +- .../openapitools/client/model/Position.java | 2 +- .../client/model/PublicTrade.java | 2 +- .../openapitools/client/model/Settlement.java | 2 +- .../client/model/TradesVolumes.java | 2 +- .../client/model/TransferItem.java | 2 +- .../org/openapitools/client/model/Types.java | 2 +- .../openapitools/client/model/UserTrade.java | 2 +- .../openapitools/client/model/Withdrawal.java | 2 +- .../client/request/DeleteRequest.java | 2 +- .../client/request/GetRequest.java | 2 +- .../client/request/PatchRequest.java | 2 +- .../client/request/PostRequest.java | 2 +- .../client/request/PutRequest.java | 2 +- aspnetcore/.openapi-generator/VERSION | 2 +- aspnetcore/Org.OpenAPITools.sln | 10 +- .../Controllers/AccountManagementApi.cs | 2 +- .../Controllers/AuthenticationApi.cs | 2 +- .../Controllers/InternalApi.cs | 2 +- .../Controllers/MarketDataApi.cs | 2 +- .../Controllers/PrivateApi.cs | 2 +- .../Org.OpenAPITools/Controllers/PublicApi.cs | 2 +- .../Controllers/SupportingApi.cs | 2 +- .../Controllers/TradingApi.cs | 2 +- .../Org.OpenAPITools/Controllers/WalletApi.cs | 2 +- .../Models/AddressBookItem.cs | 10 +- .../Org.OpenAPITools/Models/BookSummary.cs | 2 +- .../src/Org.OpenAPITools/Models/Currency.cs | 6 +- .../Models/CurrencyPortfolio.cs | 6 +- .../Models/CurrencyWithdrawalPriorities.cs | 2 +- .../src/Org.OpenAPITools/Models/Deposit.cs | 10 +- .../src/Org.OpenAPITools/Models/Instrument.cs | 22 +- .../Org.OpenAPITools/Models/KeyNumberPair.cs | 2 +- .../src/Org.OpenAPITools/Models/Order.cs | 30 +- .../Models/OrderIdInitialMarginPair.cs | 2 +- .../src/Org.OpenAPITools/Models/Portfolio.cs | 2 +- .../Org.OpenAPITools/Models/PortfolioEth.cs | 6 +- .../src/Org.OpenAPITools/Models/Position.cs | 10 +- .../Org.OpenAPITools/Models/PublicTrade.cs | 10 +- .../src/Org.OpenAPITools/Models/Settlement.cs | 6 +- .../Org.OpenAPITools/Models/TradesVolumes.cs | 6 +- .../Org.OpenAPITools/Models/TransferItem.cs | 18 +- .../src/Org.OpenAPITools/Models/Types.cs | 2 +- .../src/Org.OpenAPITools/Models/UserTrade.cs | 26 +- .../src/Org.OpenAPITools/Models/Withdrawal.cs | 10 +- aspnetcore/src/Org.OpenAPITools/Startup.cs | 2 +- c/.openapi-generator/VERSION | 2 +- clojure/.openapi-generator/VERSION | 2 +- cpp-qt5-client/.openapi-generator-ignore | 23 + cpp-qt5-client/.openapi-generator/VERSION | 1 + .../client/OAIAccountManagementApi.cpp | 921 +++++ .../client/OAIAccountManagementApi.h | 147 + .../client/OAIAddress_book_item.cpp | 171 + cpp-qt5-client/client/OAIAddress_book_item.h | 87 + .../client/OAIAuthenticationApi.cpp | 182 + cpp-qt5-client/client/OAIAuthenticationApi.h | 57 + cpp-qt5-client/client/OAIBook_summary.cpp | 523 +++ cpp-qt5-client/client/OAIBook_summary.h | 215 + cpp-qt5-client/client/OAICurrency.cpp | 282 ++ cpp-qt5-client/client/OAICurrency.h | 129 + .../client/OAICurrency_portfolio.cpp | 259 ++ cpp-qt5-client/client/OAICurrency_portfolio.h | 119 + .../OAICurrency_withdrawal_priorities.cpp | 127 + .../OAICurrency_withdrawal_priorities.h | 71 + cpp-qt5-client/client/OAIDeposit.cpp | 237 ++ cpp-qt5-client/client/OAIDeposit.h | 111 + cpp-qt5-client/client/OAIEnum.h | 64 + cpp-qt5-client/client/OAIHelpers.cpp | 349 ++ cpp-qt5-client/client/OAIHelpers.h | 163 + cpp-qt5-client/client/OAIHttpRequest.cpp | 333 ++ cpp-qt5-client/client/OAIHttpRequest.h | 94 + cpp-qt5-client/client/OAIInstrument.cpp | 369 ++ cpp-qt5-client/client/OAIInstrument.h | 159 + cpp-qt5-client/client/OAIInternalApi.cpp | 707 ++++ cpp-qt5-client/client/OAIInternalApi.h | 111 + cpp-qt5-client/client/OAIKey_number_pair.cpp | 127 + cpp-qt5-client/client/OAIKey_number_pair.h | 71 + cpp-qt5-client/client/OAIMarketDataApi.cpp | 1283 ++++++ cpp-qt5-client/client/OAIMarketDataApi.h | 159 + cpp-qt5-client/client/OAIObject.h | 66 + cpp-qt5-client/client/OAIOrder.cpp | 677 +++ cpp-qt5-client/client/OAIOrder.h | 271 ++ .../OAIOrder_id_initial_margin_pair.cpp | 127 + .../client/OAIOrder_id_initial_margin_pair.h | 71 + cpp-qt5-client/client/OAIPortfolio.cpp | 127 + cpp-qt5-client/client/OAIPortfolio.h | 71 + cpp-qt5-client/client/OAIPortfolio_eth.cpp | 259 ++ cpp-qt5-client/client/OAIPortfolio_eth.h | 119 + cpp-qt5-client/client/OAIPosition.cpp | 501 +++ cpp-qt5-client/client/OAIPosition.h | 207 + cpp-qt5-client/client/OAIPrivateApi.cpp | 3669 +++++++++++++++++ cpp-qt5-client/client/OAIPrivateApi.h | 363 ++ cpp-qt5-client/client/OAIPublicApi.cpp | 1628 ++++++++ cpp-qt5-client/client/OAIPublicApi.h | 189 + cpp-qt5-client/client/OAIPublic_trade.cpp | 303 ++ cpp-qt5-client/client/OAIPublic_trade.h | 135 + cpp-qt5-client/client/OAISettlement.cpp | 391 ++ cpp-qt5-client/client/OAISettlement.h | 167 + cpp-qt5-client/client/OAISupportingApi.cpp | 147 + cpp-qt5-client/client/OAISupportingApi.h | 63 + cpp-qt5-client/client/OAITrades_volumes.cpp | 171 + cpp-qt5-client/client/OAITrades_volumes.h | 87 + cpp-qt5-client/client/OAITradingApi.cpp | 1823 ++++++++ cpp-qt5-client/client/OAITradingApi.h | 183 + cpp-qt5-client/client/OAITransfer_item.cpp | 281 ++ cpp-qt5-client/client/OAITransfer_item.h | 127 + cpp-qt5-client/client/OAITypes.cpp | 83 + cpp-qt5-client/client/OAITypes.h | 54 + cpp-qt5-client/client/OAIUser_trade.cpp | 501 +++ cpp-qt5-client/client/OAIUser_trade.h | 207 + cpp-qt5-client/client/OAIWalletApi.cpp | 1007 +++++ cpp-qt5-client/client/OAIWalletApi.h | 135 + cpp-qt5-client/client/OAIWithdrawal.cpp | 325 ++ cpp-qt5-client/client/OAIWithdrawal.h | 143 + cpp-qt5-client/client/client.pri | 76 + cpp-restsdk/.openapi-generator/VERSION | 2 +- cpp-restsdk/ApiClient.cpp | 4 +- cpp-restsdk/ApiClient.h | 4 +- cpp-restsdk/ApiConfiguration.cpp | 4 +- cpp-restsdk/ApiConfiguration.h | 4 +- cpp-restsdk/ApiException.cpp | 4 +- cpp-restsdk/ApiException.h | 4 +- cpp-restsdk/CMakeLists.txt | 2 +- cpp-restsdk/HttpContent.cpp | 4 +- cpp-restsdk/HttpContent.h | 4 +- cpp-restsdk/IHttpBody.h | 4 +- cpp-restsdk/JsonBody.cpp | 4 +- cpp-restsdk/JsonBody.h | 4 +- cpp-restsdk/ModelBase.cpp | 4 +- cpp-restsdk/ModelBase.h | 4 +- cpp-restsdk/MultipartFormData.cpp | 4 +- cpp-restsdk/MultipartFormData.h | 4 +- cpp-restsdk/Object.cpp | 4 +- cpp-restsdk/Object.h | 4 +- cpp-restsdk/api/AccountManagementApi.cpp | 4 +- cpp-restsdk/api/AccountManagementApi.h | 4 +- cpp-restsdk/api/AuthenticationApi.cpp | 4 +- cpp-restsdk/api/AuthenticationApi.h | 4 +- cpp-restsdk/api/InternalApi.cpp | 4 +- cpp-restsdk/api/InternalApi.h | 4 +- cpp-restsdk/api/MarketDataApi.cpp | 4 +- cpp-restsdk/api/MarketDataApi.h | 4 +- cpp-restsdk/api/PrivateApi.cpp | 4 +- cpp-restsdk/api/PrivateApi.h | 4 +- cpp-restsdk/api/PublicApi.cpp | 4 +- cpp-restsdk/api/PublicApi.h | 4 +- cpp-restsdk/api/SupportingApi.cpp | 4 +- cpp-restsdk/api/SupportingApi.h | 4 +- cpp-restsdk/api/TradingApi.cpp | 4 +- cpp-restsdk/api/TradingApi.h | 4 +- cpp-restsdk/api/WalletApi.cpp | 4 +- cpp-restsdk/api/WalletApi.h | 4 +- cpp-restsdk/model/Address_book_item.cpp | 4 +- cpp-restsdk/model/Address_book_item.h | 4 +- cpp-restsdk/model/Book_summary.cpp | 4 +- cpp-restsdk/model/Book_summary.h | 4 +- cpp-restsdk/model/Currency.cpp | 4 +- cpp-restsdk/model/Currency.h | 4 +- cpp-restsdk/model/Currency_portfolio.cpp | 4 +- cpp-restsdk/model/Currency_portfolio.h | 4 +- .../model/Currency_withdrawal_priorities.cpp | 4 +- .../model/Currency_withdrawal_priorities.h | 4 +- cpp-restsdk/model/Deposit.cpp | 4 +- cpp-restsdk/model/Deposit.h | 4 +- cpp-restsdk/model/Instrument.cpp | 4 +- cpp-restsdk/model/Instrument.h | 4 +- cpp-restsdk/model/Key_number_pair.cpp | 4 +- cpp-restsdk/model/Key_number_pair.h | 4 +- cpp-restsdk/model/Order.cpp | 4 +- cpp-restsdk/model/Order.h | 4 +- .../model/Order_id_initial_margin_pair.cpp | 4 +- .../model/Order_id_initial_margin_pair.h | 4 +- cpp-restsdk/model/Portfolio.cpp | 4 +- cpp-restsdk/model/Portfolio.h | 4 +- cpp-restsdk/model/Portfolio_eth.cpp | 4 +- cpp-restsdk/model/Portfolio_eth.h | 4 +- cpp-restsdk/model/Position.cpp | 4 +- cpp-restsdk/model/Position.h | 4 +- cpp-restsdk/model/Public_trade.cpp | 4 +- cpp-restsdk/model/Public_trade.h | 4 +- cpp-restsdk/model/Settlement.cpp | 4 +- cpp-restsdk/model/Settlement.h | 4 +- cpp-restsdk/model/Trades_volumes.cpp | 4 +- cpp-restsdk/model/Trades_volumes.h | 4 +- cpp-restsdk/model/Transfer_item.cpp | 4 +- cpp-restsdk/model/Transfer_item.h | 4 +- cpp-restsdk/model/Types.cpp | 4 +- cpp-restsdk/model/Types.h | 4 +- cpp-restsdk/model/User_trade.cpp | 4 +- cpp-restsdk/model/User_trade.h | 4 +- cpp-restsdk/model/Withdrawal.cpp | 4 +- cpp-restsdk/model/Withdrawal.h | 4 +- csharp/.openapi-generator/VERSION | 2 +- csharp/Org.OpenAPITools.sln | 10 +- csharp/README.md | 10 +- csharp/docs/AccountManagementApi.md | 160 +- csharp/docs/AuthenticationApi.md | 10 +- csharp/docs/InternalApi.md | 100 +- csharp/docs/MarketDataApi.md | 180 +- csharp/docs/PrivateApi.md | 520 ++- csharp/docs/PublicApi.md | 230 +- csharp/docs/SupportingApi.md | 20 +- csharp/docs/TradingApi.md | 220 +- csharp/docs/WalletApi.md | 140 +- .../Org.OpenAPITools.Test.csproj | 4 +- .../Api/AccountManagementApi.cs | 2 +- .../Org.OpenAPITools/Api/AuthenticationApi.cs | 2 +- .../src/Org.OpenAPITools/Api/InternalApi.cs | 2 +- .../src/Org.OpenAPITools/Api/MarketDataApi.cs | 2 +- csharp/src/Org.OpenAPITools/Api/PrivateApi.cs | 2 +- csharp/src/Org.OpenAPITools/Api/PublicApi.cs | 2 +- .../src/Org.OpenAPITools/Api/SupportingApi.cs | 2 +- csharp/src/Org.OpenAPITools/Api/TradingApi.cs | 2 +- csharp/src/Org.OpenAPITools/Api/WalletApi.cs | 2 +- .../src/Org.OpenAPITools/Client/ApiClient.cs | 2 +- .../Org.OpenAPITools/Client/ApiException.cs | 2 +- .../Org.OpenAPITools/Client/ApiResponse.cs | 2 +- .../Org.OpenAPITools/Client/Configuration.cs | 2 +- .../Client/ExceptionFactory.cs | 2 +- .../Client/GlobalConfiguration.cs | 2 +- .../Org.OpenAPITools/Client/IApiAccessor.cs | 2 +- .../Client/IReadableConfiguration.cs | 2 +- .../Client/OpenAPIDateConverter.cs | 2 +- .../Org.OpenAPITools/Model/AddressBookItem.cs | 2 +- .../src/Org.OpenAPITools/Model/BookSummary.cs | 2 +- csharp/src/Org.OpenAPITools/Model/Currency.cs | 2 +- .../Model/CurrencyPortfolio.cs | 2 +- .../Model/CurrencyWithdrawalPriorities.cs | 2 +- csharp/src/Org.OpenAPITools/Model/Deposit.cs | 2 +- .../src/Org.OpenAPITools/Model/Instrument.cs | 2 +- .../Org.OpenAPITools/Model/KeyNumberPair.cs | 2 +- csharp/src/Org.OpenAPITools/Model/Order.cs | 2 +- .../Model/OrderIdInitialMarginPair.cs | 2 +- .../src/Org.OpenAPITools/Model/Portfolio.cs | 2 +- .../Org.OpenAPITools/Model/PortfolioEth.cs | 2 +- csharp/src/Org.OpenAPITools/Model/Position.cs | 2 +- .../src/Org.OpenAPITools/Model/PublicTrade.cs | 2 +- .../src/Org.OpenAPITools/Model/Settlement.cs | 2 +- .../Org.OpenAPITools/Model/TradesVolumes.cs | 2 +- .../Org.OpenAPITools/Model/TransferItem.cs | 2 +- csharp/src/Org.OpenAPITools/Model/Types.cs | 2 +- .../src/Org.OpenAPITools/Model/UserTrade.cs | 2 +- .../src/Org.OpenAPITools/Model/Withdrawal.cs | 2 +- .../Org.OpenAPITools/Org.OpenAPITools.csproj | 6 +- erlang-client/.openapi-generator/VERSION | 2 +- go/.openapi-generator/VERSION | 2 +- go/api_account_management.go | 33 +- go/api_authentication.go | 3 +- go/api_internal.go | 21 +- go/api_market_data.go | 37 +- go/api_private.go | 105 +- go/api_public.go | 47 +- go/api_supporting.go | 5 +- go/api_trading.go | 45 +- go/api_wallet.go | 29 +- go/client.go | 2 +- java/.openapi-generator/VERSION | 2 +- java/README.md | 2 +- java/docs/AccountManagementApi.md | 905 ++-- java/docs/AuthenticationApi.md | 77 +- java/docs/InternalApi.md | 592 ++- java/docs/MarketDataApi.md | 1078 +++-- java/docs/PrivateApi.md | 3124 ++++++++------ java/docs/PublicApi.md | 1379 ++++--- java/docs/SupportingApi.md | 110 +- java/docs/TradingApi.md | 1377 ++++--- java/docs/WalletApi.md | 838 ++-- .../org/openapitools/client/ApiCallback.java | 2 +- .../org/openapitools/client/ApiClient.java | 4 +- .../org/openapitools/client/ApiException.java | 4 +- .../org/openapitools/client/ApiResponse.java | 2 +- .../openapitools/client/Configuration.java | 4 +- .../client/GzipRequestInterceptor.java | 2 +- .../java/org/openapitools/client/JSON.java | 2 +- .../java/org/openapitools/client/Pair.java | 4 +- .../client/ProgressRequestBody.java | 2 +- .../client/ProgressResponseBody.java | 2 +- .../org/openapitools/client/StringUtil.java | 4 +- .../client/api/AccountManagementApi.java | 334 +- .../client/api/AuthenticationApi.java | 26 +- .../openapitools/client/api/InternalApi.java | 202 +- .../client/api/MarketDataApi.java | 362 +- .../openapitools/client/api/PrivateApi.java | 1058 ++++- .../openapitools/client/api/PublicApi.java | 466 ++- .../client/api/SupportingApi.java | 42 +- .../openapitools/client/api/TradingApi.java | 446 +- .../openapitools/client/api/WalletApi.java | 282 +- .../openapitools/client/auth/ApiKeyAuth.java | 4 +- .../client/auth/Authentication.java | 2 +- .../client/auth/HttpBasicAuth.java | 2 +- .../client/auth/HttpBearerAuth.java | 4 +- .../client/model/AddressBookItem.java | 4 +- .../client/model/BookSummary.java | 4 +- .../openapitools/client/model/Currency.java | 4 +- .../client/model/CurrencyPortfolio.java | 4 +- .../model/CurrencyWithdrawalPriorities.java | 4 +- .../openapitools/client/model/Deposit.java | 4 +- .../openapitools/client/model/Instrument.java | 4 +- .../client/model/KeyNumberPair.java | 4 +- .../org/openapitools/client/model/Order.java | 4 +- .../model/OrderIdInitialMarginPair.java | 4 +- .../openapitools/client/model/Portfolio.java | 4 +- .../client/model/PortfolioEth.java | 4 +- .../openapitools/client/model/Position.java | 4 +- .../client/model/PublicTrade.java | 4 +- .../openapitools/client/model/Settlement.java | 4 +- .../client/model/TradesVolumes.java | 4 +- .../client/model/TransferItem.java | 4 +- .../org/openapitools/client/model/Types.java | 4 +- .../openapitools/client/model/UserTrade.java | 4 +- .../openapitools/client/model/Withdrawal.java | 4 +- javascript/.openapi-generator/VERSION | 2 +- javascript/src/ApiClient.js | 5 +- javascript/src/api/AccountManagementApi.js | 2 +- javascript/src/api/AuthenticationApi.js | 2 +- javascript/src/api/InternalApi.js | 2 +- javascript/src/api/MarketDataApi.js | 2 +- javascript/src/api/PrivateApi.js | 2 +- javascript/src/api/PublicApi.js | 2 +- javascript/src/api/SupportingApi.js | 2 +- javascript/src/api/TradingApi.js | 2 +- javascript/src/api/WalletApi.js | 2 +- javascript/src/index.js | 2 +- javascript/src/model/AddressBookItem.js | 2 +- javascript/src/model/BookSummary.js | 2 +- javascript/src/model/Currency.js | 2 +- javascript/src/model/CurrencyPortfolio.js | 2 +- .../src/model/CurrencyWithdrawalPriorities.js | 2 +- javascript/src/model/Deposit.js | 2 +- javascript/src/model/Instrument.js | 2 +- javascript/src/model/KeyNumberPair.js | 2 +- javascript/src/model/Order.js | 2 +- .../src/model/OrderIdInitialMarginPair.js | 2 +- javascript/src/model/Portfolio.js | 2 +- javascript/src/model/PortfolioEth.js | 2 +- javascript/src/model/Position.js | 2 +- javascript/src/model/PublicTrade.js | 2 +- javascript/src/model/Settlement.js | 2 +- javascript/src/model/TradesVolumes.js | 2 +- javascript/src/model/TransferItem.js | 2 +- javascript/src/model/Types.js | 2 +- javascript/src/model/UserTrade.js | 2 +- javascript/src/model/Withdrawal.js | 2 +- kotlin/.openapi-generator/VERSION | 2 +- kotlin/README.md | 2 +- kotlin/build.gradle | 9 +- .../client/apis/AccountManagementApi.kt | 46 +- .../client/apis/AuthenticationApi.kt | 16 +- .../openapitools/client/apis/InternalApi.kt | 34 +- .../openapitools/client/apis/MarketDataApi.kt | 50 +- .../openapitools/client/apis/PrivateApi.kt | 118 +- .../org/openapitools/client/apis/PublicApi.kt | 60 +- .../openapitools/client/apis/SupportingApi.kt | 18 +- .../openapitools/client/apis/TradingApi.kt | 58 +- .../org/openapitools/client/apis/WalletApi.kt | 42 +- .../client/infrastructure/ApiClient.kt | 126 +- .../client/infrastructure/LocalDateAdapter.kt | 19 + .../infrastructure/LocalDateTimeAdapter.kt | 19 + .../client/infrastructure/RequestConfig.kt | 2 +- .../client/infrastructure/Serializer.kt | 12 +- .../client/infrastructure/UUIDAdapter.kt | 13 + .../client/models/AddressBookItem.kt | 2 +- .../openapitools/client/models/BookSummary.kt | 2 +- .../openapitools/client/models/Currency.kt | 2 +- .../client/models/CurrencyPortfolio.kt | 2 +- .../models/CurrencyWithdrawalPriorities.kt | 2 +- .../org/openapitools/client/models/Deposit.kt | 2 +- .../openapitools/client/models/Instrument.kt | 2 +- .../client/models/KeyNumberPair.kt | 2 +- .../org/openapitools/client/models/Order.kt | 2 +- .../client/models/OrderIdInitialMarginPair.kt | 2 +- .../openapitools/client/models/Portfolio.kt | 2 +- .../client/models/PortfolioEth.kt | 2 +- .../openapitools/client/models/Position.kt | 2 +- .../openapitools/client/models/PublicTrade.kt | 2 +- .../openapitools/client/models/Settlement.kt | 2 +- .../client/models/TradesVolumes.kt | 2 +- .../client/models/TransferItem.kt | 2 +- .../org/openapitools/client/models/Types.kt | 2 +- .../openapitools/client/models/UserTrade.kt | 2 +- .../openapitools/client/models/Withdrawal.kt | 2 +- objc/.openapi-generator/VERSION | 2 +- .../Api/OAIAccountManagementApi.h | 2 +- objc/OpenAPIClient/Api/OAIAuthenticationApi.h | 2 +- objc/OpenAPIClient/Api/OAIInternalApi.h | 2 +- objc/OpenAPIClient/Api/OAIMarketDataApi.h | 2 +- objc/OpenAPIClient/Api/OAIPrivateApi.h | 2 +- objc/OpenAPIClient/Api/OAIPublicApi.h | 2 +- objc/OpenAPIClient/Api/OAISupportingApi.h | 2 +- objc/OpenAPIClient/Api/OAITradingApi.h | 2 +- objc/OpenAPIClient/Api/OAIWalletApi.h | 2 +- .../Core/JSONValueTransformer+ISO8601.h | 2 +- objc/OpenAPIClient/Core/OAIApi.h | 2 +- objc/OpenAPIClient/Core/OAIApiClient.h | 2 +- objc/OpenAPIClient/Core/OAIConfiguration.h | 2 +- .../Core/OAIDefaultConfiguration.h | 2 +- .../Core/OAIJSONRequestSerializer.h | 2 +- objc/OpenAPIClient/Core/OAILogger.h | 2 +- objc/OpenAPIClient/Core/OAIObject.h | 2 +- .../Core/OAIQueryParamCollection.h | 2 +- .../Core/OAIResponseDeserializer.h | 2 +- objc/OpenAPIClient/Core/OAISanitizer.h | 2 +- objc/OpenAPIClient/Model/OAIAddressBookItem.h | 2 +- objc/OpenAPIClient/Model/OAIBookSummary.h | 2 +- objc/OpenAPIClient/Model/OAICurrency.h | 2 +- .../Model/OAICurrencyPortfolio.h | 2 +- .../Model/OAICurrencyWithdrawalPriorities.h | 2 +- objc/OpenAPIClient/Model/OAIDeposit.h | 2 +- objc/OpenAPIClient/Model/OAIInstrument.h | 2 +- objc/OpenAPIClient/Model/OAIKeyNumberPair.h | 2 +- objc/OpenAPIClient/Model/OAIOrder.h | 2 +- .../Model/OAIOrderIdInitialMarginPair.h | 2 +- objc/OpenAPIClient/Model/OAIPortfolio.h | 2 +- objc/OpenAPIClient/Model/OAIPortfolioEth.h | 2 +- objc/OpenAPIClient/Model/OAIPosition.h | 2 +- objc/OpenAPIClient/Model/OAIPublicTrade.h | 2 +- objc/OpenAPIClient/Model/OAISettlement.h | 2 +- objc/OpenAPIClient/Model/OAITradesVolumes.h | 2 +- objc/OpenAPIClient/Model/OAITransferItem.h | 2 +- objc/OpenAPIClient/Model/OAITypes.h | 2 +- objc/OpenAPIClient/Model/OAIUserTrade.h | 2 +- objc/OpenAPIClient/Model/OAIWithdrawal.h | 2 +- php/.openapi-generator/VERSION | 2 +- php/lib/Api/AccountManagementApi.php | 4 +- php/lib/Api/AuthenticationApi.php | 4 +- php/lib/Api/InternalApi.php | 4 +- php/lib/Api/MarketDataApi.php | 4 +- php/lib/Api/PrivateApi.php | 4 +- php/lib/Api/PublicApi.php | 4 +- php/lib/Api/SupportingApi.php | 4 +- php/lib/Api/TradingApi.php | 4 +- php/lib/Api/WalletApi.php | 4 +- php/lib/ApiException.php | 4 +- php/lib/Configuration.php | 6 +- php/lib/HeaderSelector.php | 4 +- php/lib/Model/AddressBookItem.php | 4 +- php/lib/Model/BookSummary.php | 4 +- php/lib/Model/Currency.php | 4 +- php/lib/Model/CurrencyPortfolio.php | 4 +- .../Model/CurrencyWithdrawalPriorities.php | 4 +- php/lib/Model/Deposit.php | 4 +- php/lib/Model/Instrument.php | 4 +- php/lib/Model/KeyNumberPair.php | 4 +- php/lib/Model/ModelInterface.php | 4 +- php/lib/Model/Order.php | 4 +- php/lib/Model/OrderIdInitialMarginPair.php | 4 +- php/lib/Model/Portfolio.php | 4 +- php/lib/Model/PortfolioEth.php | 4 +- php/lib/Model/Position.php | 4 +- php/lib/Model/PublicTrade.php | 4 +- php/lib/Model/Settlement.php | 4 +- php/lib/Model/TradesVolumes.php | 4 +- php/lib/Model/TransferItem.php | 4 +- php/lib/Model/Types.php | 4 +- php/lib/Model/UserTrade.php | 4 +- php/lib/Model/Withdrawal.php | 4 +- php/lib/ObjectSerializer.php | 4 +- python/.openapi-generator/VERSION | 2 +- python/docs/AccountManagementApi.md | 83 + python/docs/AuthenticationApi.md | 6 + python/docs/InternalApi.md | 50 + python/docs/MarketDataApi.md | 90 + python/docs/PrivateApi.md | 264 ++ python/docs/PublicApi.md | 116 + python/docs/SupportingApi.md | 10 + python/docs/TradingApi.md | 111 + python/docs/WalletApi.md | 70 + python/openapi_client/__init__.py | 2 +- .../api/account_management_api.py | 450 +- .../openapi_client/api/authentication_api.py | 30 +- python/openapi_client/api/internal_api.py | 282 +- python/openapi_client/api/market_data_api.py | 506 ++- python/openapi_client/api/private_api.py | 1458 +++++-- python/openapi_client/api/public_api.py | 646 ++- python/openapi_client/api/supporting_api.py | 58 +- python/openapi_client/api/trading_api.py | 618 ++- python/openapi_client/api/wallet_api.py | 394 +- python/openapi_client/api_client.py | 2 +- python/openapi_client/configuration.py | 111 +- python/openapi_client/exceptions.py | 2 +- python/openapi_client/models/__init__.py | 2 +- .../models/address_book_item.py | 2 +- python/openapi_client/models/book_summary.py | 2 +- python/openapi_client/models/currency.py | 2 +- .../models/currency_portfolio.py | 2 +- .../models/currency_withdrawal_priorities.py | 2 +- python/openapi_client/models/deposit.py | 2 +- python/openapi_client/models/instrument.py | 2 +- .../openapi_client/models/key_number_pair.py | 2 +- python/openapi_client/models/order.py | 2 +- .../models/order_id_initial_margin_pair.py | 2 +- python/openapi_client/models/portfolio.py | 2 +- python/openapi_client/models/portfolio_eth.py | 2 +- python/openapi_client/models/position.py | 2 +- python/openapi_client/models/public_trade.py | 2 +- python/openapi_client/models/settlement.py | 2 +- .../openapi_client/models/trades_volumes.py | 2 +- python/openapi_client/models/transfer_item.py | 2 +- python/openapi_client/models/types.py | 2 +- python/openapi_client/models/user_trade.py | 2 +- python/openapi_client/models/withdrawal.py | 2 +- python/openapi_client/rest.py | 2 +- python/setup.py | 2 +- r/.openapi-generator/VERSION | 2 +- r/R/account_management_api.R | 2 +- r/R/address_book_item.R | 2 +- r/R/api_client.R | 2 +- r/R/authentication_api.R | 2 +- r/R/book_summary.R | 2 +- r/R/currency.R | 2 +- r/R/currency_portfolio.R | 2 +- r/R/currency_withdrawal_priorities.R | 2 +- r/R/deposit.R | 2 +- r/R/instrument.R | 2 +- r/R/internal_api.R | 2 +- r/R/key_number_pair.R | 2 +- r/R/market_data_api.R | 2 +- r/R/order.R | 2 +- r/R/order_id_initial_margin_pair.R | 2 +- r/R/portfolio.R | 2 +- r/R/portfolio_eth.R | 2 +- r/R/position.R | 2 +- r/R/private_api.R | 2 +- r/R/public_api.R | 2 +- r/R/public_trade.R | 2 +- r/R/settlement.R | 2 +- r/R/supporting_api.R | 2 +- r/R/trades_volumes.R | 2 +- r/R/trading_api.R | 2 +- r/R/transfer_item.R | 2 +- r/R/types.R | 2 +- r/R/user_trade.R | 2 +- r/R/wallet_api.R | 2 +- r/R/withdrawal.R | 2 +- ruby/.openapi-generator/VERSION | 2 +- ruby/.rubocop.yml | 2 +- ruby/README.md | 7 +- ruby/docs/AccountManagementApi.md | 80 +- ruby/docs/AuthenticationApi.md | 5 +- ruby/docs/InternalApi.md | 50 +- ruby/docs/MarketDataApi.md | 90 +- ruby/docs/PrivateApi.md | 260 +- ruby/docs/PublicApi.md | 115 +- ruby/docs/SupportingApi.md | 10 +- ruby/docs/TradingApi.md | 110 +- ruby/docs/WalletApi.md | 70 +- ruby/lib/openapi_client.rb | 4 +- .../api/account_management_api.rb | 5 +- .../openapi_client/api/authentication_api.rb | 5 +- ruby/lib/openapi_client/api/internal_api.rb | 5 +- .../lib/openapi_client/api/market_data_api.rb | 5 +- ruby/lib/openapi_client/api/private_api.rb | 5 +- ruby/lib/openapi_client/api/public_api.rb | 5 +- ruby/lib/openapi_client/api/supporting_api.rb | 5 +- ruby/lib/openapi_client/api/trading_api.rb | 5 +- ruby/lib/openapi_client/api/wallet_api.rb | 5 +- ruby/lib/openapi_client/api_client.rb | 4 +- ruby/lib/openapi_client/api_error.rb | 4 +- ruby/lib/openapi_client/configuration.rb | 9 +- .../models/address_book_item.rb | 4 +- .../lib/openapi_client/models/book_summary.rb | 4 +- ruby/lib/openapi_client/models/currency.rb | 4 +- .../models/currency_portfolio.rb | 4 +- .../models/currency_withdrawal_priorities.rb | 4 +- ruby/lib/openapi_client/models/deposit.rb | 4 +- ruby/lib/openapi_client/models/instrument.rb | 4 +- .../openapi_client/models/key_number_pair.rb | 4 +- ruby/lib/openapi_client/models/order.rb | 4 +- .../models/order_id_initial_margin_pair.rb | 4 +- ruby/lib/openapi_client/models/portfolio.rb | 4 +- .../openapi_client/models/portfolio_eth.rb | 4 +- ruby/lib/openapi_client/models/position.rb | 4 +- .../lib/openapi_client/models/public_trade.rb | 4 +- ruby/lib/openapi_client/models/settlement.rb | 4 +- .../openapi_client/models/trades_volumes.rb | 4 +- .../openapi_client/models/transfer_item.rb | 4 +- ruby/lib/openapi_client/models/types.rb | 4 +- ruby/lib/openapi_client/models/user_trade.rb | 4 +- ruby/lib/openapi_client/models/withdrawal.rb | 4 +- ruby/lib/openapi_client/version.rb | 4 +- ruby/openapi_client.gemspec | 4 +- scala-akka/.openapi-generator/VERSION | 2 +- .../client/api/AccountManagementApi.scala | 2 +- .../client/api/AuthenticationApi.scala | 2 +- .../client/api/EnumsSerializers.scala | 2 +- .../openapitools/client/api/InternalApi.scala | 2 +- .../client/api/MarketDataApi.scala | 2 +- .../openapitools/client/api/PrivateApi.scala | 2 +- .../openapitools/client/api/PublicApi.scala | 2 +- .../client/api/SupportingApi.scala | 2 +- .../openapitools/client/api/TradingApi.scala | 2 +- .../openapitools/client/api/WalletApi.scala | 2 +- .../openapitools/client/core/ApiInvoker.scala | 2 +- .../openapitools/client/core/ApiRequest.scala | 2 +- .../client/core/ApiSettings.scala | 2 +- .../openapitools/client/core/requests.scala | 2 +- .../client/model/AddressBookItem.scala | 2 +- .../client/model/BookSummary.scala | 2 +- .../openapitools/client/model/Currency.scala | 2 +- .../client/model/CurrencyPortfolio.scala | 2 +- .../model/CurrencyWithdrawalPriorities.scala | 2 +- .../openapitools/client/model/Deposit.scala | 2 +- .../client/model/Instrument.scala | 2 +- .../client/model/KeyNumberPair.scala | 2 +- .../org/openapitools/client/model/Order.scala | 2 +- .../model/OrderIdInitialMarginPair.scala | 2 +- .../openapitools/client/model/Portfolio.scala | 2 +- .../client/model/PortfolioEth.scala | 2 +- .../openapitools/client/model/Position.scala | 2 +- .../client/model/PublicTrade.scala | 2 +- .../client/model/Settlement.scala | 2 +- .../client/model/TradesVolumes.scala | 2 +- .../client/model/TransferItem.scala | 2 +- .../org/openapitools/client/model/Types.scala | 2 +- .../openapitools/client/model/UserTrade.scala | 2 +- .../client/model/Withdrawal.scala | 2 +- swift4/.openapi-generator/VERSION | 2 +- typescript-node/.openapi-generator/VERSION | 2 +- typescript-node/api/accountManagementApi.ts | 2 +- typescript-node/api/authenticationApi.ts | 2 +- typescript-node/api/internalApi.ts | 2 +- typescript-node/api/marketDataApi.ts | 2 +- typescript-node/api/privateApi.ts | 2 +- typescript-node/api/publicApi.ts | 2 +- typescript-node/api/supportingApi.ts | 2 +- typescript-node/api/tradingApi.ts | 2 +- typescript-node/api/walletApi.ts | 2 +- typescript-node/model/addressBookItem.ts | 2 +- typescript-node/model/bookSummary.ts | 2 +- typescript-node/model/currency.ts | 2 +- typescript-node/model/currencyPortfolio.ts | 2 +- .../model/currencyWithdrawalPriorities.ts | 2 +- typescript-node/model/deposit.ts | 2 +- typescript-node/model/instrument.ts | 2 +- typescript-node/model/keyNumberPair.ts | 2 +- typescript-node/model/order.ts | 2 +- .../model/orderIdInitialMarginPair.ts | 2 +- typescript-node/model/portfolio.ts | 2 +- typescript-node/model/portfolioEth.ts | 2 +- typescript-node/model/position.ts | 2 +- typescript-node/model/publicTrade.ts | 2 +- typescript-node/model/settlement.ts | 2 +- typescript-node/model/tradesVolumes.ts | 2 +- typescript-node/model/transferItem.ts | 2 +- typescript-node/model/types.ts | 2 +- typescript-node/model/userTrade.ts | 2 +- typescript-node/model/withdrawal.ts | 2 +- 676 files changed, 38129 insertions(+), 7265 deletions(-) create mode 100644 cpp-qt5-client/.openapi-generator-ignore create mode 100644 cpp-qt5-client/.openapi-generator/VERSION create mode 100644 cpp-qt5-client/client/OAIAccountManagementApi.cpp create mode 100644 cpp-qt5-client/client/OAIAccountManagementApi.h create mode 100644 cpp-qt5-client/client/OAIAddress_book_item.cpp create mode 100644 cpp-qt5-client/client/OAIAddress_book_item.h create mode 100644 cpp-qt5-client/client/OAIAuthenticationApi.cpp create mode 100644 cpp-qt5-client/client/OAIAuthenticationApi.h create mode 100644 cpp-qt5-client/client/OAIBook_summary.cpp create mode 100644 cpp-qt5-client/client/OAIBook_summary.h create mode 100644 cpp-qt5-client/client/OAICurrency.cpp create mode 100644 cpp-qt5-client/client/OAICurrency.h create mode 100644 cpp-qt5-client/client/OAICurrency_portfolio.cpp create mode 100644 cpp-qt5-client/client/OAICurrency_portfolio.h create mode 100644 cpp-qt5-client/client/OAICurrency_withdrawal_priorities.cpp create mode 100644 cpp-qt5-client/client/OAICurrency_withdrawal_priorities.h create mode 100644 cpp-qt5-client/client/OAIDeposit.cpp create mode 100644 cpp-qt5-client/client/OAIDeposit.h create mode 100644 cpp-qt5-client/client/OAIEnum.h create mode 100644 cpp-qt5-client/client/OAIHelpers.cpp create mode 100644 cpp-qt5-client/client/OAIHelpers.h create mode 100644 cpp-qt5-client/client/OAIHttpRequest.cpp create mode 100644 cpp-qt5-client/client/OAIHttpRequest.h create mode 100644 cpp-qt5-client/client/OAIInstrument.cpp create mode 100644 cpp-qt5-client/client/OAIInstrument.h create mode 100644 cpp-qt5-client/client/OAIInternalApi.cpp create mode 100644 cpp-qt5-client/client/OAIInternalApi.h create mode 100644 cpp-qt5-client/client/OAIKey_number_pair.cpp create mode 100644 cpp-qt5-client/client/OAIKey_number_pair.h create mode 100644 cpp-qt5-client/client/OAIMarketDataApi.cpp create mode 100644 cpp-qt5-client/client/OAIMarketDataApi.h create mode 100644 cpp-qt5-client/client/OAIObject.h create mode 100644 cpp-qt5-client/client/OAIOrder.cpp create mode 100644 cpp-qt5-client/client/OAIOrder.h create mode 100644 cpp-qt5-client/client/OAIOrder_id_initial_margin_pair.cpp create mode 100644 cpp-qt5-client/client/OAIOrder_id_initial_margin_pair.h create mode 100644 cpp-qt5-client/client/OAIPortfolio.cpp create mode 100644 cpp-qt5-client/client/OAIPortfolio.h create mode 100644 cpp-qt5-client/client/OAIPortfolio_eth.cpp create mode 100644 cpp-qt5-client/client/OAIPortfolio_eth.h create mode 100644 cpp-qt5-client/client/OAIPosition.cpp create mode 100644 cpp-qt5-client/client/OAIPosition.h create mode 100644 cpp-qt5-client/client/OAIPrivateApi.cpp create mode 100644 cpp-qt5-client/client/OAIPrivateApi.h create mode 100644 cpp-qt5-client/client/OAIPublicApi.cpp create mode 100644 cpp-qt5-client/client/OAIPublicApi.h create mode 100644 cpp-qt5-client/client/OAIPublic_trade.cpp create mode 100644 cpp-qt5-client/client/OAIPublic_trade.h create mode 100644 cpp-qt5-client/client/OAISettlement.cpp create mode 100644 cpp-qt5-client/client/OAISettlement.h create mode 100644 cpp-qt5-client/client/OAISupportingApi.cpp create mode 100644 cpp-qt5-client/client/OAISupportingApi.h create mode 100644 cpp-qt5-client/client/OAITrades_volumes.cpp create mode 100644 cpp-qt5-client/client/OAITrades_volumes.h create mode 100644 cpp-qt5-client/client/OAITradingApi.cpp create mode 100644 cpp-qt5-client/client/OAITradingApi.h create mode 100644 cpp-qt5-client/client/OAITransfer_item.cpp create mode 100644 cpp-qt5-client/client/OAITransfer_item.h create mode 100644 cpp-qt5-client/client/OAITypes.cpp create mode 100644 cpp-qt5-client/client/OAITypes.h create mode 100644 cpp-qt5-client/client/OAIUser_trade.cpp create mode 100644 cpp-qt5-client/client/OAIUser_trade.h create mode 100644 cpp-qt5-client/client/OAIWalletApi.cpp create mode 100644 cpp-qt5-client/client/OAIWalletApi.h create mode 100644 cpp-qt5-client/client/OAIWithdrawal.cpp create mode 100644 cpp-qt5-client/client/OAIWithdrawal.h create mode 100644 cpp-qt5-client/client/client.pri create mode 100644 kotlin/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt create mode 100644 kotlin/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt create mode 100644 kotlin/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt diff --git a/README.md b/README.md index 715f720..2eafc34 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ The access token is valid for a certain time, read more about the scope of acces * ASP.NET Core * C * Clojure +* C++ Qt5 * C++ REST SDK * C# * Erlang diff --git a/android/.openapi-generator/VERSION b/android/.openapi-generator/VERSION index afa6365..d96260b 100644 --- a/android/.openapi-generator/VERSION +++ b/android/.openapi-generator/VERSION @@ -1 +1 @@ -4.0.0-SNAPSHOT \ No newline at end of file +4.0.2-SNAPSHOT \ No newline at end of file diff --git a/android/src/main/java/org/openapitools/client/ApiException.java b/android/src/main/java/org/openapitools/client/ApiException.java index 1ad115f..2ef3f03 100644 --- a/android/src/main/java/org/openapitools/client/ApiException.java +++ b/android/src/main/java/org/openapitools/client/ApiException.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/ApiInvoker.java b/android/src/main/java/org/openapitools/client/ApiInvoker.java index d796b91..992e029 100644 --- a/android/src/main/java/org/openapitools/client/ApiInvoker.java +++ b/android/src/main/java/org/openapitools/client/ApiInvoker.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/JsonUtil.java b/android/src/main/java/org/openapitools/client/JsonUtil.java index 3de749a..2345468 100644 --- a/android/src/main/java/org/openapitools/client/JsonUtil.java +++ b/android/src/main/java/org/openapitools/client/JsonUtil.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/Pair.java b/android/src/main/java/org/openapitools/client/Pair.java index 23b2aa5..fb35ae0 100644 --- a/android/src/main/java/org/openapitools/client/Pair.java +++ b/android/src/main/java/org/openapitools/client/Pair.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/api/AccountManagementApi.java b/android/src/main/java/org/openapitools/client/api/AccountManagementApi.java index 761e72c..c497660 100644 --- a/android/src/main/java/org/openapitools/client/api/AccountManagementApi.java +++ b/android/src/main/java/org/openapitools/client/api/AccountManagementApi.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/api/AuthenticationApi.java b/android/src/main/java/org/openapitools/client/api/AuthenticationApi.java index 9c83456..149dd7f 100644 --- a/android/src/main/java/org/openapitools/client/api/AuthenticationApi.java +++ b/android/src/main/java/org/openapitools/client/api/AuthenticationApi.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/api/InternalApi.java b/android/src/main/java/org/openapitools/client/api/InternalApi.java index f700ca2..127c538 100644 --- a/android/src/main/java/org/openapitools/client/api/InternalApi.java +++ b/android/src/main/java/org/openapitools/client/api/InternalApi.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/api/MarketDataApi.java b/android/src/main/java/org/openapitools/client/api/MarketDataApi.java index 23ceafc..c681a8c 100644 --- a/android/src/main/java/org/openapitools/client/api/MarketDataApi.java +++ b/android/src/main/java/org/openapitools/client/api/MarketDataApi.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/api/PrivateApi.java b/android/src/main/java/org/openapitools/client/api/PrivateApi.java index 19d6801..29646bc 100644 --- a/android/src/main/java/org/openapitools/client/api/PrivateApi.java +++ b/android/src/main/java/org/openapitools/client/api/PrivateApi.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/api/PublicApi.java b/android/src/main/java/org/openapitools/client/api/PublicApi.java index 17f0d2c..4b909ee 100644 --- a/android/src/main/java/org/openapitools/client/api/PublicApi.java +++ b/android/src/main/java/org/openapitools/client/api/PublicApi.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/api/SupportingApi.java b/android/src/main/java/org/openapitools/client/api/SupportingApi.java index 26e5de6..9c91b87 100644 --- a/android/src/main/java/org/openapitools/client/api/SupportingApi.java +++ b/android/src/main/java/org/openapitools/client/api/SupportingApi.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/api/TradingApi.java b/android/src/main/java/org/openapitools/client/api/TradingApi.java index 4d645d6..a681f4d 100644 --- a/android/src/main/java/org/openapitools/client/api/TradingApi.java +++ b/android/src/main/java/org/openapitools/client/api/TradingApi.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/api/WalletApi.java b/android/src/main/java/org/openapitools/client/api/WalletApi.java index 6659feb..a38b4b0 100644 --- a/android/src/main/java/org/openapitools/client/api/WalletApi.java +++ b/android/src/main/java/org/openapitools/client/api/WalletApi.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java b/android/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java index 8c692a5..b2c728a 100644 --- a/android/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java +++ b/android/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/auth/Authentication.java b/android/src/main/java/org/openapitools/client/auth/Authentication.java index ae2c15c..c7eadab 100644 --- a/android/src/main/java/org/openapitools/client/auth/Authentication.java +++ b/android/src/main/java/org/openapitools/client/auth/Authentication.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java b/android/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java index df89dbc..26b6672 100644 --- a/android/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java +++ b/android/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/model/AddressBookItem.java b/android/src/main/java/org/openapitools/client/model/AddressBookItem.java index 5747665..68b21c3 100644 --- a/android/src/main/java/org/openapitools/client/model/AddressBookItem.java +++ b/android/src/main/java/org/openapitools/client/model/AddressBookItem.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/model/BookSummary.java b/android/src/main/java/org/openapitools/client/model/BookSummary.java index 5baab8f..b3d82b6 100644 --- a/android/src/main/java/org/openapitools/client/model/BookSummary.java +++ b/android/src/main/java/org/openapitools/client/model/BookSummary.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/model/Currency.java b/android/src/main/java/org/openapitools/client/model/Currency.java index c011bcc..6dea3b8 100644 --- a/android/src/main/java/org/openapitools/client/model/Currency.java +++ b/android/src/main/java/org/openapitools/client/model/Currency.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/model/CurrencyPortfolio.java b/android/src/main/java/org/openapitools/client/model/CurrencyPortfolio.java index 71e8270..1d2fd89 100644 --- a/android/src/main/java/org/openapitools/client/model/CurrencyPortfolio.java +++ b/android/src/main/java/org/openapitools/client/model/CurrencyPortfolio.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/model/CurrencyWithdrawalPriorities.java b/android/src/main/java/org/openapitools/client/model/CurrencyWithdrawalPriorities.java index 2ba6b1b..d874273 100644 --- a/android/src/main/java/org/openapitools/client/model/CurrencyWithdrawalPriorities.java +++ b/android/src/main/java/org/openapitools/client/model/CurrencyWithdrawalPriorities.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/model/Deposit.java b/android/src/main/java/org/openapitools/client/model/Deposit.java index 1fad865..4440747 100644 --- a/android/src/main/java/org/openapitools/client/model/Deposit.java +++ b/android/src/main/java/org/openapitools/client/model/Deposit.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/model/Instrument.java b/android/src/main/java/org/openapitools/client/model/Instrument.java index aeaae02..c311d92 100644 --- a/android/src/main/java/org/openapitools/client/model/Instrument.java +++ b/android/src/main/java/org/openapitools/client/model/Instrument.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/model/KeyNumberPair.java b/android/src/main/java/org/openapitools/client/model/KeyNumberPair.java index b9a050b..4888d9b 100644 --- a/android/src/main/java/org/openapitools/client/model/KeyNumberPair.java +++ b/android/src/main/java/org/openapitools/client/model/KeyNumberPair.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/model/Order.java b/android/src/main/java/org/openapitools/client/model/Order.java index bb540a4..4a38b2b 100644 --- a/android/src/main/java/org/openapitools/client/model/Order.java +++ b/android/src/main/java/org/openapitools/client/model/Order.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/model/OrderIdInitialMarginPair.java b/android/src/main/java/org/openapitools/client/model/OrderIdInitialMarginPair.java index ffb9e56..b1c3da2 100644 --- a/android/src/main/java/org/openapitools/client/model/OrderIdInitialMarginPair.java +++ b/android/src/main/java/org/openapitools/client/model/OrderIdInitialMarginPair.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/model/Portfolio.java b/android/src/main/java/org/openapitools/client/model/Portfolio.java index 515a0e5..7e7955b 100644 --- a/android/src/main/java/org/openapitools/client/model/Portfolio.java +++ b/android/src/main/java/org/openapitools/client/model/Portfolio.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/model/PortfolioEth.java b/android/src/main/java/org/openapitools/client/model/PortfolioEth.java index 44520ff..156941a 100644 --- a/android/src/main/java/org/openapitools/client/model/PortfolioEth.java +++ b/android/src/main/java/org/openapitools/client/model/PortfolioEth.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/model/Position.java b/android/src/main/java/org/openapitools/client/model/Position.java index 2a182b0..d462813 100644 --- a/android/src/main/java/org/openapitools/client/model/Position.java +++ b/android/src/main/java/org/openapitools/client/model/Position.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/model/PublicTrade.java b/android/src/main/java/org/openapitools/client/model/PublicTrade.java index 4046b28..213d38c 100644 --- a/android/src/main/java/org/openapitools/client/model/PublicTrade.java +++ b/android/src/main/java/org/openapitools/client/model/PublicTrade.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/model/Settlement.java b/android/src/main/java/org/openapitools/client/model/Settlement.java index 3f20093..58c37d4 100644 --- a/android/src/main/java/org/openapitools/client/model/Settlement.java +++ b/android/src/main/java/org/openapitools/client/model/Settlement.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/model/TradesVolumes.java b/android/src/main/java/org/openapitools/client/model/TradesVolumes.java index 8e08e15..8b5a2a1 100644 --- a/android/src/main/java/org/openapitools/client/model/TradesVolumes.java +++ b/android/src/main/java/org/openapitools/client/model/TradesVolumes.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/model/TransferItem.java b/android/src/main/java/org/openapitools/client/model/TransferItem.java index 26d1201..13dd589 100644 --- a/android/src/main/java/org/openapitools/client/model/TransferItem.java +++ b/android/src/main/java/org/openapitools/client/model/TransferItem.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/model/Types.java b/android/src/main/java/org/openapitools/client/model/Types.java index acea279..6c30d31 100644 --- a/android/src/main/java/org/openapitools/client/model/Types.java +++ b/android/src/main/java/org/openapitools/client/model/Types.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/model/UserTrade.java b/android/src/main/java/org/openapitools/client/model/UserTrade.java index ef17502..fde7fa6 100644 --- a/android/src/main/java/org/openapitools/client/model/UserTrade.java +++ b/android/src/main/java/org/openapitools/client/model/UserTrade.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/model/Withdrawal.java b/android/src/main/java/org/openapitools/client/model/Withdrawal.java index 850487e..7b8e34e 100644 --- a/android/src/main/java/org/openapitools/client/model/Withdrawal.java +++ b/android/src/main/java/org/openapitools/client/model/Withdrawal.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/request/DeleteRequest.java b/android/src/main/java/org/openapitools/client/request/DeleteRequest.java index 4b4eaf2..1ac389e 100644 --- a/android/src/main/java/org/openapitools/client/request/DeleteRequest.java +++ b/android/src/main/java/org/openapitools/client/request/DeleteRequest.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/request/GetRequest.java b/android/src/main/java/org/openapitools/client/request/GetRequest.java index 928fb75..0e13485 100644 --- a/android/src/main/java/org/openapitools/client/request/GetRequest.java +++ b/android/src/main/java/org/openapitools/client/request/GetRequest.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/request/PatchRequest.java b/android/src/main/java/org/openapitools/client/request/PatchRequest.java index b8cddea..57e6e0e 100644 --- a/android/src/main/java/org/openapitools/client/request/PatchRequest.java +++ b/android/src/main/java/org/openapitools/client/request/PatchRequest.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/request/PostRequest.java b/android/src/main/java/org/openapitools/client/request/PostRequest.java index 43402d5..1ada4d8 100644 --- a/android/src/main/java/org/openapitools/client/request/PostRequest.java +++ b/android/src/main/java/org/openapitools/client/request/PostRequest.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/android/src/main/java/org/openapitools/client/request/PutRequest.java b/android/src/main/java/org/openapitools/client/request/PutRequest.java index b0a710c..2a9d8c0 100644 --- a/android/src/main/java/org/openapitools/client/request/PutRequest.java +++ b/android/src/main/java/org/openapitools/client/request/PutRequest.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/aspnetcore/.openapi-generator/VERSION b/aspnetcore/.openapi-generator/VERSION index afa6365..d96260b 100644 --- a/aspnetcore/.openapi-generator/VERSION +++ b/aspnetcore/.openapi-generator/VERSION @@ -1 +1 @@ -4.0.0-SNAPSHOT \ No newline at end of file +4.0.2-SNAPSHOT \ No newline at end of file diff --git a/aspnetcore/Org.OpenAPITools.sln b/aspnetcore/Org.OpenAPITools.sln index 3c4a445..55ff238 100644 --- a/aspnetcore/Org.OpenAPITools.sln +++ b/aspnetcore/Org.OpenAPITools.sln @@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.27428.2043 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools", "src\Org.OpenAPITools\Org.OpenAPITools.csproj", "{37768FBA-1121-4EFF-9E1B-379B41A0D93D}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools", "src\Org.OpenAPITools\Org.OpenAPITools.csproj", "{3374A196-0F51-4436-8BDB-136BD965491F}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -11,10 +11,10 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {37768FBA-1121-4EFF-9E1B-379B41A0D93D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {37768FBA-1121-4EFF-9E1B-379B41A0D93D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {37768FBA-1121-4EFF-9E1B-379B41A0D93D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {37768FBA-1121-4EFF-9E1B-379B41A0D93D}.Release|Any CPU.Build.0 = Release|Any CPU + {3374A196-0F51-4436-8BDB-136BD965491F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3374A196-0F51-4436-8BDB-136BD965491F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3374A196-0F51-4436-8BDB-136BD965491F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3374A196-0F51-4436-8BDB-136BD965491F}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/aspnetcore/src/Org.OpenAPITools/Controllers/AccountManagementApi.cs b/aspnetcore/src/Org.OpenAPITools/Controllers/AccountManagementApi.cs index b749d71..accb10c 100644 --- a/aspnetcore/src/Org.OpenAPITools/Controllers/AccountManagementApi.cs +++ b/aspnetcore/src/Org.OpenAPITools/Controllers/AccountManagementApi.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ diff --git a/aspnetcore/src/Org.OpenAPITools/Controllers/AuthenticationApi.cs b/aspnetcore/src/Org.OpenAPITools/Controllers/AuthenticationApi.cs index 224f821..805d7dd 100644 --- a/aspnetcore/src/Org.OpenAPITools/Controllers/AuthenticationApi.cs +++ b/aspnetcore/src/Org.OpenAPITools/Controllers/AuthenticationApi.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ diff --git a/aspnetcore/src/Org.OpenAPITools/Controllers/InternalApi.cs b/aspnetcore/src/Org.OpenAPITools/Controllers/InternalApi.cs index 4a726fb..c379c9a 100644 --- a/aspnetcore/src/Org.OpenAPITools/Controllers/InternalApi.cs +++ b/aspnetcore/src/Org.OpenAPITools/Controllers/InternalApi.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ diff --git a/aspnetcore/src/Org.OpenAPITools/Controllers/MarketDataApi.cs b/aspnetcore/src/Org.OpenAPITools/Controllers/MarketDataApi.cs index 1ee4bb9..a6c9905 100644 --- a/aspnetcore/src/Org.OpenAPITools/Controllers/MarketDataApi.cs +++ b/aspnetcore/src/Org.OpenAPITools/Controllers/MarketDataApi.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ diff --git a/aspnetcore/src/Org.OpenAPITools/Controllers/PrivateApi.cs b/aspnetcore/src/Org.OpenAPITools/Controllers/PrivateApi.cs index d6d2d45..066e511 100644 --- a/aspnetcore/src/Org.OpenAPITools/Controllers/PrivateApi.cs +++ b/aspnetcore/src/Org.OpenAPITools/Controllers/PrivateApi.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ diff --git a/aspnetcore/src/Org.OpenAPITools/Controllers/PublicApi.cs b/aspnetcore/src/Org.OpenAPITools/Controllers/PublicApi.cs index 5fe068b..f7d6e75 100644 --- a/aspnetcore/src/Org.OpenAPITools/Controllers/PublicApi.cs +++ b/aspnetcore/src/Org.OpenAPITools/Controllers/PublicApi.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ diff --git a/aspnetcore/src/Org.OpenAPITools/Controllers/SupportingApi.cs b/aspnetcore/src/Org.OpenAPITools/Controllers/SupportingApi.cs index 531e75a..ea73e67 100644 --- a/aspnetcore/src/Org.OpenAPITools/Controllers/SupportingApi.cs +++ b/aspnetcore/src/Org.OpenAPITools/Controllers/SupportingApi.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ diff --git a/aspnetcore/src/Org.OpenAPITools/Controllers/TradingApi.cs b/aspnetcore/src/Org.OpenAPITools/Controllers/TradingApi.cs index cc794d0..879fde0 100644 --- a/aspnetcore/src/Org.OpenAPITools/Controllers/TradingApi.cs +++ b/aspnetcore/src/Org.OpenAPITools/Controllers/TradingApi.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ diff --git a/aspnetcore/src/Org.OpenAPITools/Controllers/WalletApi.cs b/aspnetcore/src/Org.OpenAPITools/Controllers/WalletApi.cs index 2c96066..9a88b7d 100644 --- a/aspnetcore/src/Org.OpenAPITools/Controllers/WalletApi.cs +++ b/aspnetcore/src/Org.OpenAPITools/Controllers/WalletApi.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ diff --git a/aspnetcore/src/Org.OpenAPITools/Models/AddressBookItem.cs b/aspnetcore/src/Org.OpenAPITools/Models/AddressBookItem.cs index a1f6d6b..5881917 100644 --- a/aspnetcore/src/Org.OpenAPITools/Models/AddressBookItem.cs +++ b/aspnetcore/src/Org.OpenAPITools/Models/AddressBookItem.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ @@ -147,7 +147,7 @@ public bool Equals(AddressBookItem other) return ( Currency == other.Currency || - Currency != null && + Currency.Equals(other.Currency) ) && ( @@ -157,7 +157,7 @@ public bool Equals(AddressBookItem other) ) && ( Type == other.Type || - Type != null && + Type.Equals(other.Type) ) && ( @@ -177,11 +177,11 @@ public override int GetHashCode() { var hashCode = 41; // Suitable nullity checks etc, of course :) - if (Currency != null) + hashCode = hashCode * 59 + Currency.GetHashCode(); if (Address != null) hashCode = hashCode * 59 + Address.GetHashCode(); - if (Type != null) + hashCode = hashCode * 59 + Type.GetHashCode(); if (CreationTimestamp != null) hashCode = hashCode * 59 + CreationTimestamp.GetHashCode(); diff --git a/aspnetcore/src/Org.OpenAPITools/Models/BookSummary.cs b/aspnetcore/src/Org.OpenAPITools/Models/BookSummary.cs index c2949dd..8567c9c 100644 --- a/aspnetcore/src/Org.OpenAPITools/Models/BookSummary.cs +++ b/aspnetcore/src/Org.OpenAPITools/Models/BookSummary.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ diff --git a/aspnetcore/src/Org.OpenAPITools/Models/Currency.cs b/aspnetcore/src/Org.OpenAPITools/Models/Currency.cs index 655e245..2862733 100644 --- a/aspnetcore/src/Org.OpenAPITools/Models/Currency.cs +++ b/aspnetcore/src/Org.OpenAPITools/Models/Currency.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ @@ -207,7 +207,7 @@ public bool Equals(Currency other) ) && ( CoinType == other.CoinType || - CoinType != null && + CoinType.Equals(other.CoinType) ); } @@ -238,7 +238,7 @@ public override int GetHashCode() hashCode = hashCode * 59 + FeePrecision.GetHashCode(); if (WithdrawalPriorities != null) hashCode = hashCode * 59 + WithdrawalPriorities.GetHashCode(); - if (CoinType != null) + hashCode = hashCode * 59 + CoinType.GetHashCode(); return hashCode; } diff --git a/aspnetcore/src/Org.OpenAPITools/Models/CurrencyPortfolio.cs b/aspnetcore/src/Org.OpenAPITools/Models/CurrencyPortfolio.cs index 036e47e..88ecdf2 100644 --- a/aspnetcore/src/Org.OpenAPITools/Models/CurrencyPortfolio.cs +++ b/aspnetcore/src/Org.OpenAPITools/Models/CurrencyPortfolio.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ @@ -174,7 +174,7 @@ public bool Equals(CurrencyPortfolio other) ) && ( Currency == other.Currency || - Currency != null && + Currency.Equals(other.Currency) ) && ( @@ -212,7 +212,7 @@ public override int GetHashCode() hashCode = hashCode * 59 + InitialMargin.GetHashCode(); if (AvailableFunds != null) hashCode = hashCode * 59 + AvailableFunds.GetHashCode(); - if (Currency != null) + hashCode = hashCode * 59 + Currency.GetHashCode(); if (MarginBalance != null) hashCode = hashCode * 59 + MarginBalance.GetHashCode(); diff --git a/aspnetcore/src/Org.OpenAPITools/Models/CurrencyWithdrawalPriorities.cs b/aspnetcore/src/Org.OpenAPITools/Models/CurrencyWithdrawalPriorities.cs index 75165cf..9767d15 100644 --- a/aspnetcore/src/Org.OpenAPITools/Models/CurrencyWithdrawalPriorities.cs +++ b/aspnetcore/src/Org.OpenAPITools/Models/CurrencyWithdrawalPriorities.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ diff --git a/aspnetcore/src/Org.OpenAPITools/Models/Deposit.cs b/aspnetcore/src/Org.OpenAPITools/Models/Deposit.cs index 2263c83..998d223 100644 --- a/aspnetcore/src/Org.OpenAPITools/Models/Deposit.cs +++ b/aspnetcore/src/Org.OpenAPITools/Models/Deposit.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ @@ -192,7 +192,7 @@ public bool Equals(Deposit other) ) && ( State == other.State || - State != null && + State.Equals(other.State) ) && ( @@ -202,7 +202,7 @@ public bool Equals(Deposit other) ) && ( Currency == other.Currency || - Currency != null && + Currency.Equals(other.Currency) ) && ( @@ -234,11 +234,11 @@ public override int GetHashCode() // Suitable nullity checks etc, of course :) if (UpdatedTimestamp != null) hashCode = hashCode * 59 + UpdatedTimestamp.GetHashCode(); - if (State != null) + hashCode = hashCode * 59 + State.GetHashCode(); if (ReceivedTimestamp != null) hashCode = hashCode * 59 + ReceivedTimestamp.GetHashCode(); - if (Currency != null) + hashCode = hashCode * 59 + Currency.GetHashCode(); if (Address != null) hashCode = hashCode * 59 + Address.GetHashCode(); diff --git a/aspnetcore/src/Org.OpenAPITools/Models/Instrument.cs b/aspnetcore/src/Org.OpenAPITools/Models/Instrument.cs index 41ef1cd..b39c7ff 100644 --- a/aspnetcore/src/Org.OpenAPITools/Models/Instrument.cs +++ b/aspnetcore/src/Org.OpenAPITools/Models/Instrument.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ @@ -290,12 +290,12 @@ public bool Equals(Instrument other) return ( QuoteCurrency == other.QuoteCurrency || - QuoteCurrency != null && + QuoteCurrency.Equals(other.QuoteCurrency) ) && ( Kind == other.Kind || - Kind != null && + Kind.Equals(other.Kind) ) && ( @@ -315,7 +315,7 @@ public bool Equals(Instrument other) ) && ( OptionType == other.OptionType || - OptionType != null && + OptionType.Equals(other.OptionType) ) && ( @@ -330,7 +330,7 @@ public bool Equals(Instrument other) ) && ( SettlementPeriod == other.SettlementPeriod || - SettlementPeriod != null && + SettlementPeriod.Equals(other.SettlementPeriod) ) && ( @@ -340,7 +340,7 @@ public bool Equals(Instrument other) ) && ( BaseCurrency == other.BaseCurrency || - BaseCurrency != null && + BaseCurrency.Equals(other.BaseCurrency) ) && ( @@ -365,9 +365,9 @@ public override int GetHashCode() { var hashCode = 41; // Suitable nullity checks etc, of course :) - if (QuoteCurrency != null) + hashCode = hashCode * 59 + QuoteCurrency.GetHashCode(); - if (Kind != null) + hashCode = hashCode * 59 + Kind.GetHashCode(); if (TickSize != null) hashCode = hashCode * 59 + TickSize.GetHashCode(); @@ -375,17 +375,17 @@ public override int GetHashCode() hashCode = hashCode * 59 + ContractSize.GetHashCode(); if (IsActive != null) hashCode = hashCode * 59 + IsActive.GetHashCode(); - if (OptionType != null) + hashCode = hashCode * 59 + OptionType.GetHashCode(); if (MinTradeAmount != null) hashCode = hashCode * 59 + MinTradeAmount.GetHashCode(); if (InstrumentName != null) hashCode = hashCode * 59 + InstrumentName.GetHashCode(); - if (SettlementPeriod != null) + hashCode = hashCode * 59 + SettlementPeriod.GetHashCode(); if (Strike != null) hashCode = hashCode * 59 + Strike.GetHashCode(); - if (BaseCurrency != null) + hashCode = hashCode * 59 + BaseCurrency.GetHashCode(); if (CreationTimestamp != null) hashCode = hashCode * 59 + CreationTimestamp.GetHashCode(); diff --git a/aspnetcore/src/Org.OpenAPITools/Models/KeyNumberPair.cs b/aspnetcore/src/Org.OpenAPITools/Models/KeyNumberPair.cs index 972d11e..efb18a5 100644 --- a/aspnetcore/src/Org.OpenAPITools/Models/KeyNumberPair.cs +++ b/aspnetcore/src/Org.OpenAPITools/Models/KeyNumberPair.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ diff --git a/aspnetcore/src/Org.OpenAPITools/Models/Order.cs b/aspnetcore/src/Org.OpenAPITools/Models/Order.cs index 5c0cb79..61c2760 100644 --- a/aspnetcore/src/Org.OpenAPITools/Models/Order.cs +++ b/aspnetcore/src/Org.OpenAPITools/Models/Order.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ @@ -488,7 +488,7 @@ public bool Equals(Order other) return ( Direction == other.Direction || - Direction != null && + Direction.Equals(other.Direction) ) && ( @@ -513,7 +513,7 @@ public bool Equals(Order other) ) && ( TimeInForce == other.TimeInForce || - TimeInForce != null && + TimeInForce.Equals(other.TimeInForce) ) && ( @@ -523,7 +523,7 @@ public bool Equals(Order other) ) && ( OrderState == other.OrderState || - OrderState != null && + OrderState.Equals(other.OrderState) ) && ( @@ -533,7 +533,7 @@ public bool Equals(Order other) ) && ( Advanced == other.Advanced || - Advanced != null && + Advanced.Equals(other.Advanced) ) && ( @@ -553,7 +553,7 @@ public bool Equals(Order other) ) && ( OrderType == other.OrderType || - OrderType != null && + OrderType.Equals(other.OrderType) ) && ( @@ -563,7 +563,7 @@ public bool Equals(Order other) ) && ( OriginalOrderType == other.OriginalOrderType || - OriginalOrderType != null && + OriginalOrderType.Equals(other.OriginalOrderType) ) && ( @@ -603,7 +603,7 @@ public bool Equals(Order other) ) && ( Trigger == other.Trigger || - Trigger != null && + Trigger.Equals(other.Trigger) ) && ( @@ -633,7 +633,7 @@ public override int GetHashCode() { var hashCode = 41; // Suitable nullity checks etc, of course :) - if (Direction != null) + hashCode = hashCode * 59 + Direction.GetHashCode(); if (ReduceOnly != null) hashCode = hashCode * 59 + ReduceOnly.GetHashCode(); @@ -643,15 +643,15 @@ public override int GetHashCode() hashCode = hashCode * 59 + OrderId.GetHashCode(); if (Price != null) hashCode = hashCode * 59 + Price.GetHashCode(); - if (TimeInForce != null) + hashCode = hashCode * 59 + TimeInForce.GetHashCode(); if (Api != null) hashCode = hashCode * 59 + Api.GetHashCode(); - if (OrderState != null) + hashCode = hashCode * 59 + OrderState.GetHashCode(); if (Implv != null) hashCode = hashCode * 59 + Implv.GetHashCode(); - if (Advanced != null) + hashCode = hashCode * 59 + Advanced.GetHashCode(); if (PostOnly != null) hashCode = hashCode * 59 + PostOnly.GetHashCode(); @@ -659,11 +659,11 @@ public override int GetHashCode() hashCode = hashCode * 59 + Usd.GetHashCode(); if (StopPrice != null) hashCode = hashCode * 59 + StopPrice.GetHashCode(); - if (OrderType != null) + hashCode = hashCode * 59 + OrderType.GetHashCode(); if (LastUpdateTimestamp != null) hashCode = hashCode * 59 + LastUpdateTimestamp.GetHashCode(); - if (OriginalOrderType != null) + hashCode = hashCode * 59 + OriginalOrderType.GetHashCode(); if (MaxShow != null) hashCode = hashCode * 59 + MaxShow.GetHashCode(); @@ -679,7 +679,7 @@ public override int GetHashCode() hashCode = hashCode * 59 + Commission.GetHashCode(); if (Amount != null) hashCode = hashCode * 59 + Amount.GetHashCode(); - if (Trigger != null) + hashCode = hashCode * 59 + Trigger.GetHashCode(); if (InstrumentName != null) hashCode = hashCode * 59 + InstrumentName.GetHashCode(); diff --git a/aspnetcore/src/Org.OpenAPITools/Models/OrderIdInitialMarginPair.cs b/aspnetcore/src/Org.OpenAPITools/Models/OrderIdInitialMarginPair.cs index 4928d84..c1a7e72 100644 --- a/aspnetcore/src/Org.OpenAPITools/Models/OrderIdInitialMarginPair.cs +++ b/aspnetcore/src/Org.OpenAPITools/Models/OrderIdInitialMarginPair.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ diff --git a/aspnetcore/src/Org.OpenAPITools/Models/Portfolio.cs b/aspnetcore/src/Org.OpenAPITools/Models/Portfolio.cs index 58483a0..86d2eec 100644 --- a/aspnetcore/src/Org.OpenAPITools/Models/Portfolio.cs +++ b/aspnetcore/src/Org.OpenAPITools/Models/Portfolio.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ diff --git a/aspnetcore/src/Org.OpenAPITools/Models/PortfolioEth.cs b/aspnetcore/src/Org.OpenAPITools/Models/PortfolioEth.cs index 2dcd295..f011547 100644 --- a/aspnetcore/src/Org.OpenAPITools/Models/PortfolioEth.cs +++ b/aspnetcore/src/Org.OpenAPITools/Models/PortfolioEth.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ @@ -174,7 +174,7 @@ public bool Equals(PortfolioEth other) ) && ( Currency == other.Currency || - Currency != null && + Currency.Equals(other.Currency) ) && ( @@ -212,7 +212,7 @@ public override int GetHashCode() hashCode = hashCode * 59 + InitialMargin.GetHashCode(); if (AvailableFunds != null) hashCode = hashCode * 59 + AvailableFunds.GetHashCode(); - if (Currency != null) + hashCode = hashCode * 59 + Currency.GetHashCode(); if (MarginBalance != null) hashCode = hashCode * 59 + MarginBalance.GetHashCode(); diff --git a/aspnetcore/src/Org.OpenAPITools/Models/Position.cs b/aspnetcore/src/Org.OpenAPITools/Models/Position.cs index cbb30a3..7b88e86 100644 --- a/aspnetcore/src/Org.OpenAPITools/Models/Position.cs +++ b/aspnetcore/src/Org.OpenAPITools/Models/Position.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ @@ -278,7 +278,7 @@ public bool Equals(Position other) return ( Direction == other.Direction || - Direction != null && + Direction.Equals(other.Direction) ) && ( @@ -338,7 +338,7 @@ public bool Equals(Position other) ) && ( Kind == other.Kind || - Kind != null && + Kind.Equals(other.Kind) ) && ( @@ -383,7 +383,7 @@ public override int GetHashCode() { var hashCode = 41; // Suitable nullity checks etc, of course :) - if (Direction != null) + hashCode = hashCode * 59 + Direction.GetHashCode(); if (AveragePriceUsd != null) hashCode = hashCode * 59 + AveragePriceUsd.GetHashCode(); @@ -407,7 +407,7 @@ public override int GetHashCode() hashCode = hashCode * 59 + Size.GetHashCode(); if (MaintenanceMargin != null) hashCode = hashCode * 59 + MaintenanceMargin.GetHashCode(); - if (Kind != null) + hashCode = hashCode * 59 + Kind.GetHashCode(); if (MarkPrice != null) hashCode = hashCode * 59 + MarkPrice.GetHashCode(); diff --git a/aspnetcore/src/Org.OpenAPITools/Models/PublicTrade.cs b/aspnetcore/src/Org.OpenAPITools/Models/PublicTrade.cs index f0c3877..b36ecea 100644 --- a/aspnetcore/src/Org.OpenAPITools/Models/PublicTrade.cs +++ b/aspnetcore/src/Org.OpenAPITools/Models/PublicTrade.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ @@ -213,12 +213,12 @@ public bool Equals(PublicTrade other) return ( Direction == other.Direction || - Direction != null && + Direction.Equals(other.Direction) ) && ( TickDirection == other.TickDirection || - TickDirection != null && + TickDirection.Equals(other.TickDirection) ) && ( @@ -273,9 +273,9 @@ public override int GetHashCode() { var hashCode = 41; // Suitable nullity checks etc, of course :) - if (Direction != null) + hashCode = hashCode * 59 + Direction.GetHashCode(); - if (TickDirection != null) + hashCode = hashCode * 59 + TickDirection.GetHashCode(); if (Timestamp != null) hashCode = hashCode * 59 + Timestamp.GetHashCode(); diff --git a/aspnetcore/src/Org.OpenAPITools/Models/Settlement.cs b/aspnetcore/src/Org.OpenAPITools/Models/Settlement.cs index 4264ad9..14604cf 100644 --- a/aspnetcore/src/Org.OpenAPITools/Models/Settlement.cs +++ b/aspnetcore/src/Org.OpenAPITools/Models/Settlement.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ @@ -281,7 +281,7 @@ public bool Equals(Settlement other) ) && ( Type == other.Type || - Type != null && + Type.Equals(other.Type) ); } @@ -322,7 +322,7 @@ public override int GetHashCode() hashCode = hashCode * 59 + InstrumentName.GetHashCode(); if (Position != null) hashCode = hashCode * 59 + Position.GetHashCode(); - if (Type != null) + hashCode = hashCode * 59 + Type.GetHashCode(); return hashCode; } diff --git a/aspnetcore/src/Org.OpenAPITools/Models/TradesVolumes.cs b/aspnetcore/src/Org.OpenAPITools/Models/TradesVolumes.cs index 0bdd45d..157ef83 100644 --- a/aspnetcore/src/Org.OpenAPITools/Models/TradesVolumes.cs +++ b/aspnetcore/src/Org.OpenAPITools/Models/TradesVolumes.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ @@ -137,7 +137,7 @@ public bool Equals(TradesVolumes other) ) && ( CurrencyPair == other.CurrencyPair || - CurrencyPair != null && + CurrencyPair.Equals(other.CurrencyPair) ) && ( @@ -161,7 +161,7 @@ public override int GetHashCode() hashCode = hashCode * 59 + CallsVolume.GetHashCode(); if (PutsVolume != null) hashCode = hashCode * 59 + PutsVolume.GetHashCode(); - if (CurrencyPair != null) + hashCode = hashCode * 59 + CurrencyPair.GetHashCode(); if (FuturesVolume != null) hashCode = hashCode * 59 + FuturesVolume.GetHashCode(); diff --git a/aspnetcore/src/Org.OpenAPITools/Models/TransferItem.cs b/aspnetcore/src/Org.OpenAPITools/Models/TransferItem.cs index 749d853..50fda8a 100644 --- a/aspnetcore/src/Org.OpenAPITools/Models/TransferItem.cs +++ b/aspnetcore/src/Org.OpenAPITools/Models/TransferItem.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ @@ -257,7 +257,7 @@ public bool Equals(TransferItem other) ) && ( Direction == other.Direction || - Direction != null && + Direction.Equals(other.Direction) ) && ( @@ -272,12 +272,12 @@ public bool Equals(TransferItem other) ) && ( Currency == other.Currency || - Currency != null && + Currency.Equals(other.Currency) ) && ( State == other.State || - State != null && + State.Equals(other.State) ) && ( @@ -287,7 +287,7 @@ public bool Equals(TransferItem other) ) && ( Type == other.Type || - Type != null && + Type.Equals(other.Type) ) && ( @@ -309,19 +309,19 @@ public override int GetHashCode() // Suitable nullity checks etc, of course :) if (UpdatedTimestamp != null) hashCode = hashCode * 59 + UpdatedTimestamp.GetHashCode(); - if (Direction != null) + hashCode = hashCode * 59 + Direction.GetHashCode(); if (Amount != null) hashCode = hashCode * 59 + Amount.GetHashCode(); if (OtherSide != null) hashCode = hashCode * 59 + OtherSide.GetHashCode(); - if (Currency != null) + hashCode = hashCode * 59 + Currency.GetHashCode(); - if (State != null) + hashCode = hashCode * 59 + State.GetHashCode(); if (CreatedTimestamp != null) hashCode = hashCode * 59 + CreatedTimestamp.GetHashCode(); - if (Type != null) + hashCode = hashCode * 59 + Type.GetHashCode(); if (Id != null) hashCode = hashCode * 59 + Id.GetHashCode(); diff --git a/aspnetcore/src/Org.OpenAPITools/Models/Types.cs b/aspnetcore/src/Org.OpenAPITools/Models/Types.cs index 6e83313..4daf63f 100644 --- a/aspnetcore/src/Org.OpenAPITools/Models/Types.cs +++ b/aspnetcore/src/Org.OpenAPITools/Models/Types.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ diff --git a/aspnetcore/src/Org.OpenAPITools/Models/UserTrade.cs b/aspnetcore/src/Org.OpenAPITools/Models/UserTrade.cs index 6f6c05c..4696c0e 100644 --- a/aspnetcore/src/Org.OpenAPITools/Models/UserTrade.cs +++ b/aspnetcore/src/Org.OpenAPITools/Models/UserTrade.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ @@ -405,12 +405,12 @@ public bool Equals(UserTrade other) return ( Direction == other.Direction || - Direction != null && + Direction.Equals(other.Direction) ) && ( FeeCurrency == other.FeeCurrency || - FeeCurrency != null && + FeeCurrency.Equals(other.FeeCurrency) ) && ( @@ -445,7 +445,7 @@ public bool Equals(UserTrade other) ) && ( OrderType == other.OrderType || - OrderType != null && + OrderType.Equals(other.OrderType) ) && ( @@ -460,7 +460,7 @@ public bool Equals(UserTrade other) ) && ( State == other.State || - State != null && + State.Equals(other.State) ) && ( @@ -485,7 +485,7 @@ public bool Equals(UserTrade other) ) && ( TickDirection == other.TickDirection || - TickDirection != null && + TickDirection.Equals(other.TickDirection) ) && ( @@ -495,7 +495,7 @@ public bool Equals(UserTrade other) ) && ( Liquidity == other.Liquidity || - Liquidity != null && + Liquidity.Equals(other.Liquidity) ); } @@ -510,9 +510,9 @@ public override int GetHashCode() { var hashCode = 41; // Suitable nullity checks etc, of course :) - if (Direction != null) + hashCode = hashCode * 59 + Direction.GetHashCode(); - if (FeeCurrency != null) + hashCode = hashCode * 59 + FeeCurrency.GetHashCode(); if (OrderId != null) hashCode = hashCode * 59 + OrderId.GetHashCode(); @@ -526,13 +526,13 @@ public override int GetHashCode() hashCode = hashCode * 59 + TradeId.GetHashCode(); if (Fee != null) hashCode = hashCode * 59 + Fee.GetHashCode(); - if (OrderType != null) + hashCode = hashCode * 59 + OrderType.GetHashCode(); if (TradeSeq != null) hashCode = hashCode * 59 + TradeSeq.GetHashCode(); if (SelfTrade != null) hashCode = hashCode * 59 + SelfTrade.GetHashCode(); - if (State != null) + hashCode = hashCode * 59 + State.GetHashCode(); if (Label != null) hashCode = hashCode * 59 + Label.GetHashCode(); @@ -542,11 +542,11 @@ public override int GetHashCode() hashCode = hashCode * 59 + Amount.GetHashCode(); if (InstrumentName != null) hashCode = hashCode * 59 + InstrumentName.GetHashCode(); - if (TickDirection != null) + hashCode = hashCode * 59 + TickDirection.GetHashCode(); if (MatchingId != null) hashCode = hashCode * 59 + MatchingId.GetHashCode(); - if (Liquidity != null) + hashCode = hashCode * 59 + Liquidity.GetHashCode(); return hashCode; } diff --git a/aspnetcore/src/Org.OpenAPITools/Models/Withdrawal.cs b/aspnetcore/src/Org.OpenAPITools/Models/Withdrawal.cs index cf4d58d..b223205 100644 --- a/aspnetcore/src/Org.OpenAPITools/Models/Withdrawal.cs +++ b/aspnetcore/src/Org.OpenAPITools/Models/Withdrawal.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ @@ -255,12 +255,12 @@ public bool Equals(Withdrawal other) ) && ( Currency == other.Currency || - Currency != null && + Currency.Equals(other.Currency) ) && ( State == other.State || - State != null && + State.Equals(other.State) ) && ( @@ -305,9 +305,9 @@ public override int GetHashCode() hashCode = hashCode * 59 + Amount.GetHashCode(); if (Priority != null) hashCode = hashCode * 59 + Priority.GetHashCode(); - if (Currency != null) + hashCode = hashCode * 59 + Currency.GetHashCode(); - if (State != null) + hashCode = hashCode * 59 + State.GetHashCode(); if (Address != null) hashCode = hashCode * 59 + Address.GetHashCode(); diff --git a/aspnetcore/src/Org.OpenAPITools/Startup.cs b/aspnetcore/src/Org.OpenAPITools/Startup.cs index 406b3bb..062bac5 100644 --- a/aspnetcore/src/Org.OpenAPITools/Startup.cs +++ b/aspnetcore/src/Org.OpenAPITools/Startup.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech */ diff --git a/c/.openapi-generator/VERSION b/c/.openapi-generator/VERSION index afa6365..d96260b 100644 --- a/c/.openapi-generator/VERSION +++ b/c/.openapi-generator/VERSION @@ -1 +1 @@ -4.0.0-SNAPSHOT \ No newline at end of file +4.0.2-SNAPSHOT \ No newline at end of file diff --git a/clojure/.openapi-generator/VERSION b/clojure/.openapi-generator/VERSION index afa6365..d96260b 100644 --- a/clojure/.openapi-generator/VERSION +++ b/clojure/.openapi-generator/VERSION @@ -1 +1 @@ -4.0.0-SNAPSHOT \ No newline at end of file +4.0.2-SNAPSHOT \ No newline at end of file diff --git a/cpp-qt5-client/.openapi-generator-ignore b/cpp-qt5-client/.openapi-generator-ignore new file mode 100644 index 0000000..7484ee5 --- /dev/null +++ b/cpp-qt5-client/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/cpp-qt5-client/.openapi-generator/VERSION b/cpp-qt5-client/.openapi-generator/VERSION new file mode 100644 index 0000000..d96260b --- /dev/null +++ b/cpp-qt5-client/.openapi-generator/VERSION @@ -0,0 +1 @@ +4.0.2-SNAPSHOT \ No newline at end of file diff --git a/cpp-qt5-client/client/OAIAccountManagementApi.cpp b/cpp-qt5-client/client/OAIAccountManagementApi.cpp new file mode 100644 index 0000000..1f54862 --- /dev/null +++ b/cpp-qt5-client/client/OAIAccountManagementApi.cpp @@ -0,0 +1,921 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "OAIAccountManagementApi.h" +#include "OAIHelpers.h" + +#include +#include + +namespace OpenAPI { + +OAIAccountManagementApi::OAIAccountManagementApi() : basePath("/api/v2"), + host("www.deribit.com") { + +} + +OAIAccountManagementApi::~OAIAccountManagementApi() { + +} + +OAIAccountManagementApi::OAIAccountManagementApi(const QString& host, const QString& basePath) { + this->host = host; + this->basePath = basePath; +} + +void OAIAccountManagementApi::setBasePath(const QString& basePath){ + this->basePath = basePath; +} + +void OAIAccountManagementApi::setHost(const QString& host){ + this->host = host; +} + +void OAIAccountManagementApi::addHeaders(const QString& key, const QString& value){ + defaultHeaders.insert(key, value); +} + + +void +OAIAccountManagementApi::privateChangeSubaccountNameGet(const qint32& sid, const QString& name) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/change_subaccount_name"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sid")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sid))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(name))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIAccountManagementApi::privateChangeSubaccountNameGetCallback); + + worker->execute(&input); +} + +void +OAIAccountManagementApi::privateChangeSubaccountNameGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateChangeSubaccountNameGetSignal(output); + emit privateChangeSubaccountNameGetSignalFull(worker, output); + } else { + emit privateChangeSubaccountNameGetSignalE(output, error_type, error_str); + emit privateChangeSubaccountNameGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIAccountManagementApi::privateCreateSubaccountGet() { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/create_subaccount"); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIAccountManagementApi::privateCreateSubaccountGetCallback); + + worker->execute(&input); +} + +void +OAIAccountManagementApi::privateCreateSubaccountGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateCreateSubaccountGetSignal(output); + emit privateCreateSubaccountGetSignalFull(worker, output); + } else { + emit privateCreateSubaccountGetSignalE(output, error_type, error_str); + emit privateCreateSubaccountGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIAccountManagementApi::privateDisableTfaForSubaccountGet(const qint32& sid) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/disable_tfa_for_subaccount"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sid")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sid))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIAccountManagementApi::privateDisableTfaForSubaccountGetCallback); + + worker->execute(&input); +} + +void +OAIAccountManagementApi::privateDisableTfaForSubaccountGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateDisableTfaForSubaccountGetSignal(output); + emit privateDisableTfaForSubaccountGetSignalFull(worker, output); + } else { + emit privateDisableTfaForSubaccountGetSignalE(output, error_type, error_str); + emit privateDisableTfaForSubaccountGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIAccountManagementApi::privateGetAccountSummaryGet(const QString& currency, const bool& extended) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_account_summary"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("extended")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(extended))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIAccountManagementApi::privateGetAccountSummaryGetCallback); + + worker->execute(&input); +} + +void +OAIAccountManagementApi::privateGetAccountSummaryGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetAccountSummaryGetSignal(output); + emit privateGetAccountSummaryGetSignalFull(worker, output); + } else { + emit privateGetAccountSummaryGetSignalE(output, error_type, error_str); + emit privateGetAccountSummaryGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIAccountManagementApi::privateGetEmailLanguageGet() { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_email_language"); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIAccountManagementApi::privateGetEmailLanguageGetCallback); + + worker->execute(&input); +} + +void +OAIAccountManagementApi::privateGetEmailLanguageGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetEmailLanguageGetSignal(output); + emit privateGetEmailLanguageGetSignalFull(worker, output); + } else { + emit privateGetEmailLanguageGetSignalE(output, error_type, error_str); + emit privateGetEmailLanguageGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIAccountManagementApi::privateGetNewAnnouncementsGet() { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_new_announcements"); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIAccountManagementApi::privateGetNewAnnouncementsGetCallback); + + worker->execute(&input); +} + +void +OAIAccountManagementApi::privateGetNewAnnouncementsGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetNewAnnouncementsGetSignal(output); + emit privateGetNewAnnouncementsGetSignalFull(worker, output); + } else { + emit privateGetNewAnnouncementsGetSignalE(output, error_type, error_str); + emit privateGetNewAnnouncementsGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIAccountManagementApi::privateGetPositionGet(const QString& instrument_name) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_position"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIAccountManagementApi::privateGetPositionGetCallback); + + worker->execute(&input); +} + +void +OAIAccountManagementApi::privateGetPositionGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetPositionGetSignal(output); + emit privateGetPositionGetSignalFull(worker, output); + } else { + emit privateGetPositionGetSignalE(output, error_type, error_str); + emit privateGetPositionGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIAccountManagementApi::privateGetPositionsGet(const QString& currency, const QString& kind) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_positions"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("kind")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(kind))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIAccountManagementApi::privateGetPositionsGetCallback); + + worker->execute(&input); +} + +void +OAIAccountManagementApi::privateGetPositionsGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetPositionsGetSignal(output); + emit privateGetPositionsGetSignalFull(worker, output); + } else { + emit privateGetPositionsGetSignalE(output, error_type, error_str); + emit privateGetPositionsGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIAccountManagementApi::privateGetSubaccountsGet(const bool& with_portfolio) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_subaccounts"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("with_portfolio")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(with_portfolio))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIAccountManagementApi::privateGetSubaccountsGetCallback); + + worker->execute(&input); +} + +void +OAIAccountManagementApi::privateGetSubaccountsGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetSubaccountsGetSignal(output); + emit privateGetSubaccountsGetSignalFull(worker, output); + } else { + emit privateGetSubaccountsGetSignalE(output, error_type, error_str); + emit privateGetSubaccountsGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIAccountManagementApi::privateSetAnnouncementAsReadGet(const double& announcement_id) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/set_announcement_as_read"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("announcement_id")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(announcement_id))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIAccountManagementApi::privateSetAnnouncementAsReadGetCallback); + + worker->execute(&input); +} + +void +OAIAccountManagementApi::privateSetAnnouncementAsReadGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateSetAnnouncementAsReadGetSignal(output); + emit privateSetAnnouncementAsReadGetSignalFull(worker, output); + } else { + emit privateSetAnnouncementAsReadGetSignalE(output, error_type, error_str); + emit privateSetAnnouncementAsReadGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIAccountManagementApi::privateSetEmailForSubaccountGet(const qint32& sid, const QString& email) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/set_email_for_subaccount"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sid")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sid))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("email")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(email))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIAccountManagementApi::privateSetEmailForSubaccountGetCallback); + + worker->execute(&input); +} + +void +OAIAccountManagementApi::privateSetEmailForSubaccountGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateSetEmailForSubaccountGetSignal(output); + emit privateSetEmailForSubaccountGetSignalFull(worker, output); + } else { + emit privateSetEmailForSubaccountGetSignalE(output, error_type, error_str); + emit privateSetEmailForSubaccountGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIAccountManagementApi::privateSetEmailLanguageGet(const QString& language) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/set_email_language"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("language")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(language))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIAccountManagementApi::privateSetEmailLanguageGetCallback); + + worker->execute(&input); +} + +void +OAIAccountManagementApi::privateSetEmailLanguageGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateSetEmailLanguageGetSignal(output); + emit privateSetEmailLanguageGetSignalFull(worker, output); + } else { + emit privateSetEmailLanguageGetSignalE(output, error_type, error_str); + emit privateSetEmailLanguageGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIAccountManagementApi::privateSetPasswordForSubaccountGet(const qint32& sid, const QString& password) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/set_password_for_subaccount"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sid")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sid))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("password")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(password))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIAccountManagementApi::privateSetPasswordForSubaccountGetCallback); + + worker->execute(&input); +} + +void +OAIAccountManagementApi::privateSetPasswordForSubaccountGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateSetPasswordForSubaccountGetSignal(output); + emit privateSetPasswordForSubaccountGetSignalFull(worker, output); + } else { + emit privateSetPasswordForSubaccountGetSignalE(output, error_type, error_str); + emit privateSetPasswordForSubaccountGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIAccountManagementApi::privateToggleNotificationsFromSubaccountGet(const qint32& sid, const bool& state) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/toggle_notifications_from_subaccount"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sid")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sid))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("state")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(state))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIAccountManagementApi::privateToggleNotificationsFromSubaccountGetCallback); + + worker->execute(&input); +} + +void +OAIAccountManagementApi::privateToggleNotificationsFromSubaccountGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateToggleNotificationsFromSubaccountGetSignal(output); + emit privateToggleNotificationsFromSubaccountGetSignalFull(worker, output); + } else { + emit privateToggleNotificationsFromSubaccountGetSignalE(output, error_type, error_str); + emit privateToggleNotificationsFromSubaccountGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIAccountManagementApi::privateToggleSubaccountLoginGet(const qint32& sid, const QString& state) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/toggle_subaccount_login"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sid")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sid))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("state")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(state))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIAccountManagementApi::privateToggleSubaccountLoginGetCallback); + + worker->execute(&input); +} + +void +OAIAccountManagementApi::privateToggleSubaccountLoginGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateToggleSubaccountLoginGetSignal(output); + emit privateToggleSubaccountLoginGetSignalFull(worker, output); + } else { + emit privateToggleSubaccountLoginGetSignalE(output, error_type, error_str); + emit privateToggleSubaccountLoginGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIAccountManagementApi::publicGetAnnouncementsGet() { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_announcements"); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIAccountManagementApi::publicGetAnnouncementsGetCallback); + + worker->execute(&input); +} + +void +OAIAccountManagementApi::publicGetAnnouncementsGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetAnnouncementsGetSignal(output); + emit publicGetAnnouncementsGetSignalFull(worker, output); + } else { + emit publicGetAnnouncementsGetSignalE(output, error_type, error_str); + emit publicGetAnnouncementsGetSignalEFull(worker, error_type, error_str); + } +} + + +} diff --git a/cpp-qt5-client/client/OAIAccountManagementApi.h b/cpp-qt5-client/client/OAIAccountManagementApi.h new file mode 100644 index 0000000..4f3069c --- /dev/null +++ b/cpp-qt5-client/client/OAIAccountManagementApi.h @@ -0,0 +1,147 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#ifndef OAI_OAIAccountManagementApi_H +#define OAI_OAIAccountManagementApi_H + +#include "OAIHttpRequest.h" + +#include "OAIObject.h" +#include + +#include + +namespace OpenAPI { + +class OAIAccountManagementApi: public QObject { + Q_OBJECT + +public: + OAIAccountManagementApi(); + OAIAccountManagementApi(const QString& host, const QString& basePath); + ~OAIAccountManagementApi(); + + void setBasePath(const QString& basePath); + void setHost(const QString& host); + void addHeaders(const QString& key, const QString& value); + + void privateChangeSubaccountNameGet(const qint32& sid, const QString& name); + void privateCreateSubaccountGet(); + void privateDisableTfaForSubaccountGet(const qint32& sid); + void privateGetAccountSummaryGet(const QString& currency, const bool& extended); + void privateGetEmailLanguageGet(); + void privateGetNewAnnouncementsGet(); + void privateGetPositionGet(const QString& instrument_name); + void privateGetPositionsGet(const QString& currency, const QString& kind); + void privateGetSubaccountsGet(const bool& with_portfolio); + void privateSetAnnouncementAsReadGet(const double& announcement_id); + void privateSetEmailForSubaccountGet(const qint32& sid, const QString& email); + void privateSetEmailLanguageGet(const QString& language); + void privateSetPasswordForSubaccountGet(const qint32& sid, const QString& password); + void privateToggleNotificationsFromSubaccountGet(const qint32& sid, const bool& state); + void privateToggleSubaccountLoginGet(const qint32& sid, const QString& state); + void publicGetAnnouncementsGet(); + +private: + QString basePath; + QString host; + QMap defaultHeaders; + void privateChangeSubaccountNameGetCallback (OAIHttpRequestWorker * worker); + void privateCreateSubaccountGetCallback (OAIHttpRequestWorker * worker); + void privateDisableTfaForSubaccountGetCallback (OAIHttpRequestWorker * worker); + void privateGetAccountSummaryGetCallback (OAIHttpRequestWorker * worker); + void privateGetEmailLanguageGetCallback (OAIHttpRequestWorker * worker); + void privateGetNewAnnouncementsGetCallback (OAIHttpRequestWorker * worker); + void privateGetPositionGetCallback (OAIHttpRequestWorker * worker); + void privateGetPositionsGetCallback (OAIHttpRequestWorker * worker); + void privateGetSubaccountsGetCallback (OAIHttpRequestWorker * worker); + void privateSetAnnouncementAsReadGetCallback (OAIHttpRequestWorker * worker); + void privateSetEmailForSubaccountGetCallback (OAIHttpRequestWorker * worker); + void privateSetEmailLanguageGetCallback (OAIHttpRequestWorker * worker); + void privateSetPasswordForSubaccountGetCallback (OAIHttpRequestWorker * worker); + void privateToggleNotificationsFromSubaccountGetCallback (OAIHttpRequestWorker * worker); + void privateToggleSubaccountLoginGetCallback (OAIHttpRequestWorker * worker); + void publicGetAnnouncementsGetCallback (OAIHttpRequestWorker * worker); + +signals: + void privateChangeSubaccountNameGetSignal(OAIObject summary); + void privateCreateSubaccountGetSignal(OAIObject summary); + void privateDisableTfaForSubaccountGetSignal(OAIObject summary); + void privateGetAccountSummaryGetSignal(OAIObject summary); + void privateGetEmailLanguageGetSignal(OAIObject summary); + void privateGetNewAnnouncementsGetSignal(OAIObject summary); + void privateGetPositionGetSignal(OAIObject summary); + void privateGetPositionsGetSignal(OAIObject summary); + void privateGetSubaccountsGetSignal(OAIObject summary); + void privateSetAnnouncementAsReadGetSignal(OAIObject summary); + void privateSetEmailForSubaccountGetSignal(OAIObject summary); + void privateSetEmailLanguageGetSignal(OAIObject summary); + void privateSetPasswordForSubaccountGetSignal(OAIObject summary); + void privateToggleNotificationsFromSubaccountGetSignal(OAIObject summary); + void privateToggleSubaccountLoginGetSignal(OAIObject summary); + void publicGetAnnouncementsGetSignal(OAIObject summary); + + void privateChangeSubaccountNameGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateCreateSubaccountGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateDisableTfaForSubaccountGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetAccountSummaryGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetEmailLanguageGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetNewAnnouncementsGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetPositionGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetPositionsGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetSubaccountsGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateSetAnnouncementAsReadGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateSetEmailForSubaccountGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateSetEmailLanguageGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateSetPasswordForSubaccountGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateToggleNotificationsFromSubaccountGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateToggleSubaccountLoginGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetAnnouncementsGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + + void privateChangeSubaccountNameGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCreateSubaccountGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateDisableTfaForSubaccountGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetAccountSummaryGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetEmailLanguageGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetNewAnnouncementsGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetPositionGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetPositionsGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetSubaccountsGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSetAnnouncementAsReadGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSetEmailForSubaccountGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSetEmailLanguageGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSetPasswordForSubaccountGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateToggleNotificationsFromSubaccountGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateToggleSubaccountLoginGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetAnnouncementsGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + + void privateChangeSubaccountNameGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCreateSubaccountGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateDisableTfaForSubaccountGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetAccountSummaryGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetEmailLanguageGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetNewAnnouncementsGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetPositionGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetPositionsGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetSubaccountsGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSetAnnouncementAsReadGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSetEmailForSubaccountGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSetEmailLanguageGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSetPasswordForSubaccountGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateToggleNotificationsFromSubaccountGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateToggleSubaccountLoginGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetAnnouncementsGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + +}; + +} +#endif diff --git a/cpp-qt5-client/client/OAIAddress_book_item.cpp b/cpp-qt5-client/client/OAIAddress_book_item.cpp new file mode 100644 index 0000000..512781e --- /dev/null +++ b/cpp-qt5-client/client/OAIAddress_book_item.cpp @@ -0,0 +1,171 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include "OAIAddress_book_item.h" + +#include "OAIHelpers.h" + +#include +#include +#include +#include + +namespace OpenAPI { + +OAIAddress_book_item::OAIAddress_book_item(QString json) { + this->init(); + this->fromJson(json); +} + +OAIAddress_book_item::OAIAddress_book_item() { + this->init(); +} + +OAIAddress_book_item::~OAIAddress_book_item() { + +} + +void +OAIAddress_book_item::init() { + + m_currency_isSet = false; + m_currency_isValid = false; + + m_address_isSet = false; + m_address_isValid = false; + + m_type_isSet = false; + m_type_isValid = false; + + m_creation_timestamp_isSet = false; + m_creation_timestamp_isValid = false; + } + +void +OAIAddress_book_item::fromJson(QString jsonString) { + QByteArray array (jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void +OAIAddress_book_item::fromJsonObject(QJsonObject json) { + + m_currency_isValid = ::OpenAPI::fromJsonValue(currency, json[QString("currency")]); + + + m_address_isValid = ::OpenAPI::fromJsonValue(address, json[QString("address")]); + + + m_type_isValid = ::OpenAPI::fromJsonValue(type, json[QString("type")]); + + + m_creation_timestamp_isValid = ::OpenAPI::fromJsonValue(creation_timestamp, json[QString("creation_timestamp")]); + + +} + +QString +OAIAddress_book_item::asJson () const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject +OAIAddress_book_item::asJsonObject() const { + QJsonObject obj; + if(m_currency_isSet){ + obj.insert(QString("currency"), ::OpenAPI::toJsonValue(currency)); + } + if(m_address_isSet){ + obj.insert(QString("address"), ::OpenAPI::toJsonValue(address)); + } + if(m_type_isSet){ + obj.insert(QString("type"), ::OpenAPI::toJsonValue(type)); + } + if(m_creation_timestamp_isSet){ + obj.insert(QString("creation_timestamp"), ::OpenAPI::toJsonValue(creation_timestamp)); + } + return obj; +} + + +QString +OAIAddress_book_item::getCurrency() const { + return currency; +} +void +OAIAddress_book_item::setCurrency(const QString ¤cy) { + this->currency = currency; + this->m_currency_isSet = true; +} + + +QString +OAIAddress_book_item::getAddress() const { + return address; +} +void +OAIAddress_book_item::setAddress(const QString &address) { + this->address = address; + this->m_address_isSet = true; +} + + +QString +OAIAddress_book_item::getType() const { + return type; +} +void +OAIAddress_book_item::setType(const QString &type) { + this->type = type; + this->m_type_isSet = true; +} + + +qint32 +OAIAddress_book_item::getCreationTimestamp() const { + return creation_timestamp; +} +void +OAIAddress_book_item::setCreationTimestamp(const qint32 &creation_timestamp) { + this->creation_timestamp = creation_timestamp; + this->m_creation_timestamp_isSet = true; +} + +bool +OAIAddress_book_item::isSet() const { + bool isObjectUpdated = false; + do{ + if(m_currency_isSet){ isObjectUpdated = true; break;} + + if(m_address_isSet){ isObjectUpdated = true; break;} + + if(m_type_isSet){ isObjectUpdated = true; break;} + + if(m_creation_timestamp_isSet){ isObjectUpdated = true; break;} + }while(false); + return isObjectUpdated; +} + +bool +OAIAddress_book_item::isValid() const { + // only required properties are required for the object to be considered valid + return m_currency_isValid && m_address_isValid && m_creation_timestamp_isValid && true; +} + +} + diff --git a/cpp-qt5-client/client/OAIAddress_book_item.h b/cpp-qt5-client/client/OAIAddress_book_item.h new file mode 100644 index 0000000..0fca64e --- /dev/null +++ b/cpp-qt5-client/client/OAIAddress_book_item.h @@ -0,0 +1,87 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OAIAddress_book_item.h + * + * + */ + +#ifndef OAIAddress_book_item_H +#define OAIAddress_book_item_H + +#include + + +#include + +#include "OAIObject.h" +#include "OAIEnum.h" + +namespace OpenAPI { + +class OAIAddress_book_item: public OAIObject { +public: + OAIAddress_book_item(); + OAIAddress_book_item(QString json); + ~OAIAddress_book_item() override; + + QString asJson () const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + + QString getCurrency() const; + void setCurrency(const QString ¤cy); + + + QString getAddress() const; + void setAddress(const QString &address); + + + QString getType() const; + void setType(const QString &type); + + + qint32 getCreationTimestamp() const; + void setCreationTimestamp(const qint32 &creation_timestamp); + + + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void init(); + + QString currency; + bool m_currency_isSet; + bool m_currency_isValid; + + QString address; + bool m_address_isSet; + bool m_address_isValid; + + QString type; + bool m_type_isSet; + bool m_type_isValid; + + qint32 creation_timestamp; + bool m_creation_timestamp_isSet; + bool m_creation_timestamp_isValid; + + }; + +} + +#endif // OAIAddress_book_item_H diff --git a/cpp-qt5-client/client/OAIAuthenticationApi.cpp b/cpp-qt5-client/client/OAIAuthenticationApi.cpp new file mode 100644 index 0000000..3b69e6e --- /dev/null +++ b/cpp-qt5-client/client/OAIAuthenticationApi.cpp @@ -0,0 +1,182 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "OAIAuthenticationApi.h" +#include "OAIHelpers.h" + +#include +#include + +namespace OpenAPI { + +OAIAuthenticationApi::OAIAuthenticationApi() : basePath("/api/v2"), + host("www.deribit.com") { + +} + +OAIAuthenticationApi::~OAIAuthenticationApi() { + +} + +OAIAuthenticationApi::OAIAuthenticationApi(const QString& host, const QString& basePath) { + this->host = host; + this->basePath = basePath; +} + +void OAIAuthenticationApi::setBasePath(const QString& basePath){ + this->basePath = basePath; +} + +void OAIAuthenticationApi::setHost(const QString& host){ + this->host = host; +} + +void OAIAuthenticationApi::addHeaders(const QString& key, const QString& value){ + defaultHeaders.insert(key, value); +} + + +void +OAIAuthenticationApi::publicAuthGet(const QString& grant_type, const QString& username, const QString& password, const QString& client_id, const QString& client_secret, const QString& refresh_token, const QString& timestamp, const QString& signature, const QString& nonce, const QString& state, const QString& scope) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/auth"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("grant_type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(grant_type))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("username")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(username))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("password")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(password))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("client_id")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(client_id))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("client_secret")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(client_secret))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("refresh_token")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(refresh_token))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(timestamp))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("signature")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(signature))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("nonce")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(nonce))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("state")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(state))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("scope")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(scope))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIAuthenticationApi::publicAuthGetCallback); + + worker->execute(&input); +} + +void +OAIAuthenticationApi::publicAuthGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicAuthGetSignal(output); + emit publicAuthGetSignalFull(worker, output); + } else { + emit publicAuthGetSignalE(output, error_type, error_str); + emit publicAuthGetSignalEFull(worker, error_type, error_str); + } +} + + +} diff --git a/cpp-qt5-client/client/OAIAuthenticationApi.h b/cpp-qt5-client/client/OAIAuthenticationApi.h new file mode 100644 index 0000000..ca52d6e --- /dev/null +++ b/cpp-qt5-client/client/OAIAuthenticationApi.h @@ -0,0 +1,57 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#ifndef OAI_OAIAuthenticationApi_H +#define OAI_OAIAuthenticationApi_H + +#include "OAIHttpRequest.h" + +#include "OAIObject.h" +#include + +#include + +namespace OpenAPI { + +class OAIAuthenticationApi: public QObject { + Q_OBJECT + +public: + OAIAuthenticationApi(); + OAIAuthenticationApi(const QString& host, const QString& basePath); + ~OAIAuthenticationApi(); + + void setBasePath(const QString& basePath); + void setHost(const QString& host); + void addHeaders(const QString& key, const QString& value); + + void publicAuthGet(const QString& grant_type, const QString& username, const QString& password, const QString& client_id, const QString& client_secret, const QString& refresh_token, const QString& timestamp, const QString& signature, const QString& nonce, const QString& state, const QString& scope); + +private: + QString basePath; + QString host; + QMap defaultHeaders; + void publicAuthGetCallback (OAIHttpRequestWorker * worker); + +signals: + void publicAuthGetSignal(OAIObject summary); + + void publicAuthGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + + void publicAuthGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + + void publicAuthGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + +}; + +} +#endif diff --git a/cpp-qt5-client/client/OAIBook_summary.cpp b/cpp-qt5-client/client/OAIBook_summary.cpp new file mode 100644 index 0000000..2820b78 --- /dev/null +++ b/cpp-qt5-client/client/OAIBook_summary.cpp @@ -0,0 +1,523 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include "OAIBook_summary.h" + +#include "OAIHelpers.h" + +#include +#include +#include +#include + +namespace OpenAPI { + +OAIBook_summary::OAIBook_summary(QString json) { + this->init(); + this->fromJson(json); +} + +OAIBook_summary::OAIBook_summary() { + this->init(); +} + +OAIBook_summary::~OAIBook_summary() { + +} + +void +OAIBook_summary::init() { + + m_underlying_index_isSet = false; + m_underlying_index_isValid = false; + + m_volume_isSet = false; + m_volume_isValid = false; + + m_volume_usd_isSet = false; + m_volume_usd_isValid = false; + + m_underlying_price_isSet = false; + m_underlying_price_isValid = false; + + m_bid_price_isSet = false; + m_bid_price_isValid = false; + + m_open_interest_isSet = false; + m_open_interest_isValid = false; + + m_quote_currency_isSet = false; + m_quote_currency_isValid = false; + + m_high_isSet = false; + m_high_isValid = false; + + m_estimated_delivery_price_isSet = false; + m_estimated_delivery_price_isValid = false; + + m_last_isSet = false; + m_last_isValid = false; + + m_mid_price_isSet = false; + m_mid_price_isValid = false; + + m_interest_rate_isSet = false; + m_interest_rate_isValid = false; + + m_funding_8h_isSet = false; + m_funding_8h_isValid = false; + + m_mark_price_isSet = false; + m_mark_price_isValid = false; + + m_ask_price_isSet = false; + m_ask_price_isValid = false; + + m_instrument_name_isSet = false; + m_instrument_name_isValid = false; + + m_low_isSet = false; + m_low_isValid = false; + + m_base_currency_isSet = false; + m_base_currency_isValid = false; + + m_creation_timestamp_isSet = false; + m_creation_timestamp_isValid = false; + + m_current_funding_isSet = false; + m_current_funding_isValid = false; + } + +void +OAIBook_summary::fromJson(QString jsonString) { + QByteArray array (jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void +OAIBook_summary::fromJsonObject(QJsonObject json) { + + m_underlying_index_isValid = ::OpenAPI::fromJsonValue(underlying_index, json[QString("underlying_index")]); + + + m_volume_isValid = ::OpenAPI::fromJsonValue(volume, json[QString("volume")]); + + + m_volume_usd_isValid = ::OpenAPI::fromJsonValue(volume_usd, json[QString("volume_usd")]); + + + m_underlying_price_isValid = ::OpenAPI::fromJsonValue(underlying_price, json[QString("underlying_price")]); + + + m_bid_price_isValid = ::OpenAPI::fromJsonValue(bid_price, json[QString("bid_price")]); + + + m_open_interest_isValid = ::OpenAPI::fromJsonValue(open_interest, json[QString("open_interest")]); + + + m_quote_currency_isValid = ::OpenAPI::fromJsonValue(quote_currency, json[QString("quote_currency")]); + + + m_high_isValid = ::OpenAPI::fromJsonValue(high, json[QString("high")]); + + + m_estimated_delivery_price_isValid = ::OpenAPI::fromJsonValue(estimated_delivery_price, json[QString("estimated_delivery_price")]); + + + m_last_isValid = ::OpenAPI::fromJsonValue(last, json[QString("last")]); + + + m_mid_price_isValid = ::OpenAPI::fromJsonValue(mid_price, json[QString("mid_price")]); + + + m_interest_rate_isValid = ::OpenAPI::fromJsonValue(interest_rate, json[QString("interest_rate")]); + + + m_funding_8h_isValid = ::OpenAPI::fromJsonValue(funding_8h, json[QString("funding_8h")]); + + + m_mark_price_isValid = ::OpenAPI::fromJsonValue(mark_price, json[QString("mark_price")]); + + + m_ask_price_isValid = ::OpenAPI::fromJsonValue(ask_price, json[QString("ask_price")]); + + + m_instrument_name_isValid = ::OpenAPI::fromJsonValue(instrument_name, json[QString("instrument_name")]); + + + m_low_isValid = ::OpenAPI::fromJsonValue(low, json[QString("low")]); + + + m_base_currency_isValid = ::OpenAPI::fromJsonValue(base_currency, json[QString("base_currency")]); + + + m_creation_timestamp_isValid = ::OpenAPI::fromJsonValue(creation_timestamp, json[QString("creation_timestamp")]); + + + m_current_funding_isValid = ::OpenAPI::fromJsonValue(current_funding, json[QString("current_funding")]); + + +} + +QString +OAIBook_summary::asJson () const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject +OAIBook_summary::asJsonObject() const { + QJsonObject obj; + if(m_underlying_index_isSet){ + obj.insert(QString("underlying_index"), ::OpenAPI::toJsonValue(underlying_index)); + } + if(m_volume_isSet){ + obj.insert(QString("volume"), ::OpenAPI::toJsonValue(volume)); + } + if(m_volume_usd_isSet){ + obj.insert(QString("volume_usd"), ::OpenAPI::toJsonValue(volume_usd)); + } + if(m_underlying_price_isSet){ + obj.insert(QString("underlying_price"), ::OpenAPI::toJsonValue(underlying_price)); + } + if(m_bid_price_isSet){ + obj.insert(QString("bid_price"), ::OpenAPI::toJsonValue(bid_price)); + } + if(m_open_interest_isSet){ + obj.insert(QString("open_interest"), ::OpenAPI::toJsonValue(open_interest)); + } + if(m_quote_currency_isSet){ + obj.insert(QString("quote_currency"), ::OpenAPI::toJsonValue(quote_currency)); + } + if(m_high_isSet){ + obj.insert(QString("high"), ::OpenAPI::toJsonValue(high)); + } + if(m_estimated_delivery_price_isSet){ + obj.insert(QString("estimated_delivery_price"), ::OpenAPI::toJsonValue(estimated_delivery_price)); + } + if(m_last_isSet){ + obj.insert(QString("last"), ::OpenAPI::toJsonValue(last)); + } + if(m_mid_price_isSet){ + obj.insert(QString("mid_price"), ::OpenAPI::toJsonValue(mid_price)); + } + if(m_interest_rate_isSet){ + obj.insert(QString("interest_rate"), ::OpenAPI::toJsonValue(interest_rate)); + } + if(m_funding_8h_isSet){ + obj.insert(QString("funding_8h"), ::OpenAPI::toJsonValue(funding_8h)); + } + if(m_mark_price_isSet){ + obj.insert(QString("mark_price"), ::OpenAPI::toJsonValue(mark_price)); + } + if(m_ask_price_isSet){ + obj.insert(QString("ask_price"), ::OpenAPI::toJsonValue(ask_price)); + } + if(m_instrument_name_isSet){ + obj.insert(QString("instrument_name"), ::OpenAPI::toJsonValue(instrument_name)); + } + if(m_low_isSet){ + obj.insert(QString("low"), ::OpenAPI::toJsonValue(low)); + } + if(m_base_currency_isSet){ + obj.insert(QString("base_currency"), ::OpenAPI::toJsonValue(base_currency)); + } + if(m_creation_timestamp_isSet){ + obj.insert(QString("creation_timestamp"), ::OpenAPI::toJsonValue(creation_timestamp)); + } + if(m_current_funding_isSet){ + obj.insert(QString("current_funding"), ::OpenAPI::toJsonValue(current_funding)); + } + return obj; +} + + +QString +OAIBook_summary::getUnderlyingIndex() const { + return underlying_index; +} +void +OAIBook_summary::setUnderlyingIndex(const QString &underlying_index) { + this->underlying_index = underlying_index; + this->m_underlying_index_isSet = true; +} + + +double +OAIBook_summary::getVolume() const { + return volume; +} +void +OAIBook_summary::setVolume(const double &volume) { + this->volume = volume; + this->m_volume_isSet = true; +} + + +double +OAIBook_summary::getVolumeUsd() const { + return volume_usd; +} +void +OAIBook_summary::setVolumeUsd(const double &volume_usd) { + this->volume_usd = volume_usd; + this->m_volume_usd_isSet = true; +} + + +double +OAIBook_summary::getUnderlyingPrice() const { + return underlying_price; +} +void +OAIBook_summary::setUnderlyingPrice(const double &underlying_price) { + this->underlying_price = underlying_price; + this->m_underlying_price_isSet = true; +} + + +double +OAIBook_summary::getBidPrice() const { + return bid_price; +} +void +OAIBook_summary::setBidPrice(const double &bid_price) { + this->bid_price = bid_price; + this->m_bid_price_isSet = true; +} + + +double +OAIBook_summary::getOpenInterest() const { + return open_interest; +} +void +OAIBook_summary::setOpenInterest(const double &open_interest) { + this->open_interest = open_interest; + this->m_open_interest_isSet = true; +} + + +QString +OAIBook_summary::getQuoteCurrency() const { + return quote_currency; +} +void +OAIBook_summary::setQuoteCurrency(const QString "e_currency) { + this->quote_currency = quote_currency; + this->m_quote_currency_isSet = true; +} + + +double +OAIBook_summary::getHigh() const { + return high; +} +void +OAIBook_summary::setHigh(const double &high) { + this->high = high; + this->m_high_isSet = true; +} + + +double +OAIBook_summary::getEstimatedDeliveryPrice() const { + return estimated_delivery_price; +} +void +OAIBook_summary::setEstimatedDeliveryPrice(const double &estimated_delivery_price) { + this->estimated_delivery_price = estimated_delivery_price; + this->m_estimated_delivery_price_isSet = true; +} + + +double +OAIBook_summary::getLast() const { + return last; +} +void +OAIBook_summary::setLast(const double &last) { + this->last = last; + this->m_last_isSet = true; +} + + +double +OAIBook_summary::getMidPrice() const { + return mid_price; +} +void +OAIBook_summary::setMidPrice(const double &mid_price) { + this->mid_price = mid_price; + this->m_mid_price_isSet = true; +} + + +double +OAIBook_summary::getInterestRate() const { + return interest_rate; +} +void +OAIBook_summary::setInterestRate(const double &interest_rate) { + this->interest_rate = interest_rate; + this->m_interest_rate_isSet = true; +} + + +double +OAIBook_summary::getFunding8h() const { + return funding_8h; +} +void +OAIBook_summary::setFunding8h(const double &funding_8h) { + this->funding_8h = funding_8h; + this->m_funding_8h_isSet = true; +} + + +double +OAIBook_summary::getMarkPrice() const { + return mark_price; +} +void +OAIBook_summary::setMarkPrice(const double &mark_price) { + this->mark_price = mark_price; + this->m_mark_price_isSet = true; +} + + +double +OAIBook_summary::getAskPrice() const { + return ask_price; +} +void +OAIBook_summary::setAskPrice(const double &ask_price) { + this->ask_price = ask_price; + this->m_ask_price_isSet = true; +} + + +QString +OAIBook_summary::getInstrumentName() const { + return instrument_name; +} +void +OAIBook_summary::setInstrumentName(const QString &instrument_name) { + this->instrument_name = instrument_name; + this->m_instrument_name_isSet = true; +} + + +double +OAIBook_summary::getLow() const { + return low; +} +void +OAIBook_summary::setLow(const double &low) { + this->low = low; + this->m_low_isSet = true; +} + + +QString +OAIBook_summary::getBaseCurrency() const { + return base_currency; +} +void +OAIBook_summary::setBaseCurrency(const QString &base_currency) { + this->base_currency = base_currency; + this->m_base_currency_isSet = true; +} + + +qint32 +OAIBook_summary::getCreationTimestamp() const { + return creation_timestamp; +} +void +OAIBook_summary::setCreationTimestamp(const qint32 &creation_timestamp) { + this->creation_timestamp = creation_timestamp; + this->m_creation_timestamp_isSet = true; +} + + +double +OAIBook_summary::getCurrentFunding() const { + return current_funding; +} +void +OAIBook_summary::setCurrentFunding(const double ¤t_funding) { + this->current_funding = current_funding; + this->m_current_funding_isSet = true; +} + +bool +OAIBook_summary::isSet() const { + bool isObjectUpdated = false; + do{ + if(m_underlying_index_isSet){ isObjectUpdated = true; break;} + + if(m_volume_isSet){ isObjectUpdated = true; break;} + + if(m_volume_usd_isSet){ isObjectUpdated = true; break;} + + if(m_underlying_price_isSet){ isObjectUpdated = true; break;} + + if(m_bid_price_isSet){ isObjectUpdated = true; break;} + + if(m_open_interest_isSet){ isObjectUpdated = true; break;} + + if(m_quote_currency_isSet){ isObjectUpdated = true; break;} + + if(m_high_isSet){ isObjectUpdated = true; break;} + + if(m_estimated_delivery_price_isSet){ isObjectUpdated = true; break;} + + if(m_last_isSet){ isObjectUpdated = true; break;} + + if(m_mid_price_isSet){ isObjectUpdated = true; break;} + + if(m_interest_rate_isSet){ isObjectUpdated = true; break;} + + if(m_funding_8h_isSet){ isObjectUpdated = true; break;} + + if(m_mark_price_isSet){ isObjectUpdated = true; break;} + + if(m_ask_price_isSet){ isObjectUpdated = true; break;} + + if(m_instrument_name_isSet){ isObjectUpdated = true; break;} + + if(m_low_isSet){ isObjectUpdated = true; break;} + + if(m_base_currency_isSet){ isObjectUpdated = true; break;} + + if(m_creation_timestamp_isSet){ isObjectUpdated = true; break;} + + if(m_current_funding_isSet){ isObjectUpdated = true; break;} + }while(false); + return isObjectUpdated; +} + +bool +OAIBook_summary::isValid() const { + // only required properties are required for the object to be considered valid + return m_volume_isValid && m_bid_price_isValid && m_open_interest_isValid && m_quote_currency_isValid && m_high_isValid && m_last_isValid && m_mid_price_isValid && m_mark_price_isValid && m_ask_price_isValid && m_instrument_name_isValid && m_low_isValid && m_creation_timestamp_isValid && true; +} + +} + diff --git a/cpp-qt5-client/client/OAIBook_summary.h b/cpp-qt5-client/client/OAIBook_summary.h new file mode 100644 index 0000000..11bf137 --- /dev/null +++ b/cpp-qt5-client/client/OAIBook_summary.h @@ -0,0 +1,215 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OAIBook_summary.h + * + * + */ + +#ifndef OAIBook_summary_H +#define OAIBook_summary_H + +#include + + +#include + +#include "OAIObject.h" +#include "OAIEnum.h" + +namespace OpenAPI { + +class OAIBook_summary: public OAIObject { +public: + OAIBook_summary(); + OAIBook_summary(QString json); + ~OAIBook_summary() override; + + QString asJson () const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + + QString getUnderlyingIndex() const; + void setUnderlyingIndex(const QString &underlying_index); + + + double getVolume() const; + void setVolume(const double &volume); + + + double getVolumeUsd() const; + void setVolumeUsd(const double &volume_usd); + + + double getUnderlyingPrice() const; + void setUnderlyingPrice(const double &underlying_price); + + + double getBidPrice() const; + void setBidPrice(const double &bid_price); + + + double getOpenInterest() const; + void setOpenInterest(const double &open_interest); + + + QString getQuoteCurrency() const; + void setQuoteCurrency(const QString "e_currency); + + + double getHigh() const; + void setHigh(const double &high); + + + double getEstimatedDeliveryPrice() const; + void setEstimatedDeliveryPrice(const double &estimated_delivery_price); + + + double getLast() const; + void setLast(const double &last); + + + double getMidPrice() const; + void setMidPrice(const double &mid_price); + + + double getInterestRate() const; + void setInterestRate(const double &interest_rate); + + + double getFunding8h() const; + void setFunding8h(const double &funding_8h); + + + double getMarkPrice() const; + void setMarkPrice(const double &mark_price); + + + double getAskPrice() const; + void setAskPrice(const double &ask_price); + + + QString getInstrumentName() const; + void setInstrumentName(const QString &instrument_name); + + + double getLow() const; + void setLow(const double &low); + + + QString getBaseCurrency() const; + void setBaseCurrency(const QString &base_currency); + + + qint32 getCreationTimestamp() const; + void setCreationTimestamp(const qint32 &creation_timestamp); + + + double getCurrentFunding() const; + void setCurrentFunding(const double ¤t_funding); + + + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void init(); + + QString underlying_index; + bool m_underlying_index_isSet; + bool m_underlying_index_isValid; + + double volume; + bool m_volume_isSet; + bool m_volume_isValid; + + double volume_usd; + bool m_volume_usd_isSet; + bool m_volume_usd_isValid; + + double underlying_price; + bool m_underlying_price_isSet; + bool m_underlying_price_isValid; + + double bid_price; + bool m_bid_price_isSet; + bool m_bid_price_isValid; + + double open_interest; + bool m_open_interest_isSet; + bool m_open_interest_isValid; + + QString quote_currency; + bool m_quote_currency_isSet; + bool m_quote_currency_isValid; + + double high; + bool m_high_isSet; + bool m_high_isValid; + + double estimated_delivery_price; + bool m_estimated_delivery_price_isSet; + bool m_estimated_delivery_price_isValid; + + double last; + bool m_last_isSet; + bool m_last_isValid; + + double mid_price; + bool m_mid_price_isSet; + bool m_mid_price_isValid; + + double interest_rate; + bool m_interest_rate_isSet; + bool m_interest_rate_isValid; + + double funding_8h; + bool m_funding_8h_isSet; + bool m_funding_8h_isValid; + + double mark_price; + bool m_mark_price_isSet; + bool m_mark_price_isValid; + + double ask_price; + bool m_ask_price_isSet; + bool m_ask_price_isValid; + + QString instrument_name; + bool m_instrument_name_isSet; + bool m_instrument_name_isValid; + + double low; + bool m_low_isSet; + bool m_low_isValid; + + QString base_currency; + bool m_base_currency_isSet; + bool m_base_currency_isValid; + + qint32 creation_timestamp; + bool m_creation_timestamp_isSet; + bool m_creation_timestamp_isValid; + + double current_funding; + bool m_current_funding_isSet; + bool m_current_funding_isValid; + + }; + +} + +#endif // OAIBook_summary_H diff --git a/cpp-qt5-client/client/OAICurrency.cpp b/cpp-qt5-client/client/OAICurrency.cpp new file mode 100644 index 0000000..a660e70 --- /dev/null +++ b/cpp-qt5-client/client/OAICurrency.cpp @@ -0,0 +1,282 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include "OAICurrency.h" + +#include "OAIHelpers.h" + +#include +#include +#include +#include + +namespace OpenAPI { + +OAICurrency::OAICurrency(QString json) { + this->init(); + this->fromJson(json); +} + +OAICurrency::OAICurrency() { + this->init(); +} + +OAICurrency::~OAICurrency() { + +} + +void +OAICurrency::init() { + + m_min_confirmations_isSet = false; + m_min_confirmations_isValid = false; + + m_min_withdrawal_fee_isSet = false; + m_min_withdrawal_fee_isValid = false; + + m_disabled_deposit_address_creation_isSet = false; + m_disabled_deposit_address_creation_isValid = false; + + m_currency_isSet = false; + m_currency_isValid = false; + + m_currency_long_isSet = false; + m_currency_long_isValid = false; + + m_withdrawal_fee_isSet = false; + m_withdrawal_fee_isValid = false; + + m_fee_precision_isSet = false; + m_fee_precision_isValid = false; + + m_withdrawal_priorities_isSet = false; + m_withdrawal_priorities_isValid = false; + + m_coin_type_isSet = false; + m_coin_type_isValid = false; + } + +void +OAICurrency::fromJson(QString jsonString) { + QByteArray array (jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void +OAICurrency::fromJsonObject(QJsonObject json) { + + m_min_confirmations_isValid = ::OpenAPI::fromJsonValue(min_confirmations, json[QString("min_confirmations")]); + + + m_min_withdrawal_fee_isValid = ::OpenAPI::fromJsonValue(min_withdrawal_fee, json[QString("min_withdrawal_fee")]); + + + m_disabled_deposit_address_creation_isValid = ::OpenAPI::fromJsonValue(disabled_deposit_address_creation, json[QString("disabled_deposit_address_creation")]); + + + m_currency_isValid = ::OpenAPI::fromJsonValue(currency, json[QString("currency")]); + + + m_currency_long_isValid = ::OpenAPI::fromJsonValue(currency_long, json[QString("currency_long")]); + + + m_withdrawal_fee_isValid = ::OpenAPI::fromJsonValue(withdrawal_fee, json[QString("withdrawal_fee")]); + + + m_fee_precision_isValid = ::OpenAPI::fromJsonValue(fee_precision, json[QString("fee_precision")]); + + + + m_withdrawal_priorities_isValid = ::OpenAPI::fromJsonValue(withdrawal_priorities, json[QString("withdrawal_priorities")]); + + m_coin_type_isValid = ::OpenAPI::fromJsonValue(coin_type, json[QString("coin_type")]); + + +} + +QString +OAICurrency::asJson () const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject +OAICurrency::asJsonObject() const { + QJsonObject obj; + if(m_min_confirmations_isSet){ + obj.insert(QString("min_confirmations"), ::OpenAPI::toJsonValue(min_confirmations)); + } + if(m_min_withdrawal_fee_isSet){ + obj.insert(QString("min_withdrawal_fee"), ::OpenAPI::toJsonValue(min_withdrawal_fee)); + } + if(m_disabled_deposit_address_creation_isSet){ + obj.insert(QString("disabled_deposit_address_creation"), ::OpenAPI::toJsonValue(disabled_deposit_address_creation)); + } + if(m_currency_isSet){ + obj.insert(QString("currency"), ::OpenAPI::toJsonValue(currency)); + } + if(m_currency_long_isSet){ + obj.insert(QString("currency_long"), ::OpenAPI::toJsonValue(currency_long)); + } + if(m_withdrawal_fee_isSet){ + obj.insert(QString("withdrawal_fee"), ::OpenAPI::toJsonValue(withdrawal_fee)); + } + if(m_fee_precision_isSet){ + obj.insert(QString("fee_precision"), ::OpenAPI::toJsonValue(fee_precision)); + } + + if(withdrawal_priorities.size() > 0){ + obj.insert(QString("withdrawal_priorities"), ::OpenAPI::toJsonValue(withdrawal_priorities)); + } + if(m_coin_type_isSet){ + obj.insert(QString("coin_type"), ::OpenAPI::toJsonValue(coin_type)); + } + return obj; +} + + +qint32 +OAICurrency::getMinConfirmations() const { + return min_confirmations; +} +void +OAICurrency::setMinConfirmations(const qint32 &min_confirmations) { + this->min_confirmations = min_confirmations; + this->m_min_confirmations_isSet = true; +} + + +double +OAICurrency::getMinWithdrawalFee() const { + return min_withdrawal_fee; +} +void +OAICurrency::setMinWithdrawalFee(const double &min_withdrawal_fee) { + this->min_withdrawal_fee = min_withdrawal_fee; + this->m_min_withdrawal_fee_isSet = true; +} + + +bool +OAICurrency::isDisabledDepositAddressCreation() const { + return disabled_deposit_address_creation; +} +void +OAICurrency::setDisabledDepositAddressCreation(const bool &disabled_deposit_address_creation) { + this->disabled_deposit_address_creation = disabled_deposit_address_creation; + this->m_disabled_deposit_address_creation_isSet = true; +} + + +QString +OAICurrency::getCurrency() const { + return currency; +} +void +OAICurrency::setCurrency(const QString ¤cy) { + this->currency = currency; + this->m_currency_isSet = true; +} + + +QString +OAICurrency::getCurrencyLong() const { + return currency_long; +} +void +OAICurrency::setCurrencyLong(const QString ¤cy_long) { + this->currency_long = currency_long; + this->m_currency_long_isSet = true; +} + + +double +OAICurrency::getWithdrawalFee() const { + return withdrawal_fee; +} +void +OAICurrency::setWithdrawalFee(const double &withdrawal_fee) { + this->withdrawal_fee = withdrawal_fee; + this->m_withdrawal_fee_isSet = true; +} + + +qint32 +OAICurrency::getFeePrecision() const { + return fee_precision; +} +void +OAICurrency::setFeePrecision(const qint32 &fee_precision) { + this->fee_precision = fee_precision; + this->m_fee_precision_isSet = true; +} + + +QList +OAICurrency::getWithdrawalPriorities() const { + return withdrawal_priorities; +} +void +OAICurrency::setWithdrawalPriorities(const QList &withdrawal_priorities) { + this->withdrawal_priorities = withdrawal_priorities; + this->m_withdrawal_priorities_isSet = true; +} + + +QString +OAICurrency::getCoinType() const { + return coin_type; +} +void +OAICurrency::setCoinType(const QString &coin_type) { + this->coin_type = coin_type; + this->m_coin_type_isSet = true; +} + +bool +OAICurrency::isSet() const { + bool isObjectUpdated = false; + do{ + if(m_min_confirmations_isSet){ isObjectUpdated = true; break;} + + if(m_min_withdrawal_fee_isSet){ isObjectUpdated = true; break;} + + if(m_disabled_deposit_address_creation_isSet){ isObjectUpdated = true; break;} + + if(m_currency_isSet){ isObjectUpdated = true; break;} + + if(m_currency_long_isSet){ isObjectUpdated = true; break;} + + if(m_withdrawal_fee_isSet){ isObjectUpdated = true; break;} + + if(m_fee_precision_isSet){ isObjectUpdated = true; break;} + + if(withdrawal_priorities.size() > 0){ isObjectUpdated = true; break;} + + if(m_coin_type_isSet){ isObjectUpdated = true; break;} + }while(false); + return isObjectUpdated; +} + +bool +OAICurrency::isValid() const { + // only required properties are required for the object to be considered valid + return m_currency_isValid && m_currency_long_isValid && m_withdrawal_fee_isValid && m_coin_type_isValid && true; +} + +} + diff --git a/cpp-qt5-client/client/OAICurrency.h b/cpp-qt5-client/client/OAICurrency.h new file mode 100644 index 0000000..b72f991 --- /dev/null +++ b/cpp-qt5-client/client/OAICurrency.h @@ -0,0 +1,129 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OAICurrency.h + * + * + */ + +#ifndef OAICurrency_H +#define OAICurrency_H + +#include + + +#include "OAICurrency_withdrawal_priorities.h" +#include +#include + +#include "OAIObject.h" +#include "OAIEnum.h" + +namespace OpenAPI { + +class OAICurrency: public OAIObject { +public: + OAICurrency(); + OAICurrency(QString json); + ~OAICurrency() override; + + QString asJson () const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + + qint32 getMinConfirmations() const; + void setMinConfirmations(const qint32 &min_confirmations); + + + double getMinWithdrawalFee() const; + void setMinWithdrawalFee(const double &min_withdrawal_fee); + + + bool isDisabledDepositAddressCreation() const; + void setDisabledDepositAddressCreation(const bool &disabled_deposit_address_creation); + + + QString getCurrency() const; + void setCurrency(const QString ¤cy); + + + QString getCurrencyLong() const; + void setCurrencyLong(const QString ¤cy_long); + + + double getWithdrawalFee() const; + void setWithdrawalFee(const double &withdrawal_fee); + + + qint32 getFeePrecision() const; + void setFeePrecision(const qint32 &fee_precision); + + + QList getWithdrawalPriorities() const; + void setWithdrawalPriorities(const QList &withdrawal_priorities); + + + QString getCoinType() const; + void setCoinType(const QString &coin_type); + + + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void init(); + + qint32 min_confirmations; + bool m_min_confirmations_isSet; + bool m_min_confirmations_isValid; + + double min_withdrawal_fee; + bool m_min_withdrawal_fee_isSet; + bool m_min_withdrawal_fee_isValid; + + bool disabled_deposit_address_creation; + bool m_disabled_deposit_address_creation_isSet; + bool m_disabled_deposit_address_creation_isValid; + + QString currency; + bool m_currency_isSet; + bool m_currency_isValid; + + QString currency_long; + bool m_currency_long_isSet; + bool m_currency_long_isValid; + + double withdrawal_fee; + bool m_withdrawal_fee_isSet; + bool m_withdrawal_fee_isValid; + + qint32 fee_precision; + bool m_fee_precision_isSet; + bool m_fee_precision_isValid; + + QList withdrawal_priorities; + bool m_withdrawal_priorities_isSet; + bool m_withdrawal_priorities_isValid; + + QString coin_type; + bool m_coin_type_isSet; + bool m_coin_type_isValid; + + }; + +} + +#endif // OAICurrency_H diff --git a/cpp-qt5-client/client/OAICurrency_portfolio.cpp b/cpp-qt5-client/client/OAICurrency_portfolio.cpp new file mode 100644 index 0000000..5d7db69 --- /dev/null +++ b/cpp-qt5-client/client/OAICurrency_portfolio.cpp @@ -0,0 +1,259 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include "OAICurrency_portfolio.h" + +#include "OAIHelpers.h" + +#include +#include +#include +#include + +namespace OpenAPI { + +OAICurrency_portfolio::OAICurrency_portfolio(QString json) { + this->init(); + this->fromJson(json); +} + +OAICurrency_portfolio::OAICurrency_portfolio() { + this->init(); +} + +OAICurrency_portfolio::~OAICurrency_portfolio() { + +} + +void +OAICurrency_portfolio::init() { + + m_maintenance_margin_isSet = false; + m_maintenance_margin_isValid = false; + + m_available_withdrawal_funds_isSet = false; + m_available_withdrawal_funds_isValid = false; + + m_initial_margin_isSet = false; + m_initial_margin_isValid = false; + + m_available_funds_isSet = false; + m_available_funds_isValid = false; + + m_currency_isSet = false; + m_currency_isValid = false; + + m_margin_balance_isSet = false; + m_margin_balance_isValid = false; + + m_equity_isSet = false; + m_equity_isValid = false; + + m_balance_isSet = false; + m_balance_isValid = false; + } + +void +OAICurrency_portfolio::fromJson(QString jsonString) { + QByteArray array (jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void +OAICurrency_portfolio::fromJsonObject(QJsonObject json) { + + m_maintenance_margin_isValid = ::OpenAPI::fromJsonValue(maintenance_margin, json[QString("maintenance_margin")]); + + + m_available_withdrawal_funds_isValid = ::OpenAPI::fromJsonValue(available_withdrawal_funds, json[QString("available_withdrawal_funds")]); + + + m_initial_margin_isValid = ::OpenAPI::fromJsonValue(initial_margin, json[QString("initial_margin")]); + + + m_available_funds_isValid = ::OpenAPI::fromJsonValue(available_funds, json[QString("available_funds")]); + + + m_currency_isValid = ::OpenAPI::fromJsonValue(currency, json[QString("currency")]); + + + m_margin_balance_isValid = ::OpenAPI::fromJsonValue(margin_balance, json[QString("margin_balance")]); + + + m_equity_isValid = ::OpenAPI::fromJsonValue(equity, json[QString("equity")]); + + + m_balance_isValid = ::OpenAPI::fromJsonValue(balance, json[QString("balance")]); + + +} + +QString +OAICurrency_portfolio::asJson () const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject +OAICurrency_portfolio::asJsonObject() const { + QJsonObject obj; + if(m_maintenance_margin_isSet){ + obj.insert(QString("maintenance_margin"), ::OpenAPI::toJsonValue(maintenance_margin)); + } + if(m_available_withdrawal_funds_isSet){ + obj.insert(QString("available_withdrawal_funds"), ::OpenAPI::toJsonValue(available_withdrawal_funds)); + } + if(m_initial_margin_isSet){ + obj.insert(QString("initial_margin"), ::OpenAPI::toJsonValue(initial_margin)); + } + if(m_available_funds_isSet){ + obj.insert(QString("available_funds"), ::OpenAPI::toJsonValue(available_funds)); + } + if(m_currency_isSet){ + obj.insert(QString("currency"), ::OpenAPI::toJsonValue(currency)); + } + if(m_margin_balance_isSet){ + obj.insert(QString("margin_balance"), ::OpenAPI::toJsonValue(margin_balance)); + } + if(m_equity_isSet){ + obj.insert(QString("equity"), ::OpenAPI::toJsonValue(equity)); + } + if(m_balance_isSet){ + obj.insert(QString("balance"), ::OpenAPI::toJsonValue(balance)); + } + return obj; +} + + +double +OAICurrency_portfolio::getMaintenanceMargin() const { + return maintenance_margin; +} +void +OAICurrency_portfolio::setMaintenanceMargin(const double &maintenance_margin) { + this->maintenance_margin = maintenance_margin; + this->m_maintenance_margin_isSet = true; +} + + +double +OAICurrency_portfolio::getAvailableWithdrawalFunds() const { + return available_withdrawal_funds; +} +void +OAICurrency_portfolio::setAvailableWithdrawalFunds(const double &available_withdrawal_funds) { + this->available_withdrawal_funds = available_withdrawal_funds; + this->m_available_withdrawal_funds_isSet = true; +} + + +double +OAICurrency_portfolio::getInitialMargin() const { + return initial_margin; +} +void +OAICurrency_portfolio::setInitialMargin(const double &initial_margin) { + this->initial_margin = initial_margin; + this->m_initial_margin_isSet = true; +} + + +double +OAICurrency_portfolio::getAvailableFunds() const { + return available_funds; +} +void +OAICurrency_portfolio::setAvailableFunds(const double &available_funds) { + this->available_funds = available_funds; + this->m_available_funds_isSet = true; +} + + +QString +OAICurrency_portfolio::getCurrency() const { + return currency; +} +void +OAICurrency_portfolio::setCurrency(const QString ¤cy) { + this->currency = currency; + this->m_currency_isSet = true; +} + + +double +OAICurrency_portfolio::getMarginBalance() const { + return margin_balance; +} +void +OAICurrency_portfolio::setMarginBalance(const double &margin_balance) { + this->margin_balance = margin_balance; + this->m_margin_balance_isSet = true; +} + + +double +OAICurrency_portfolio::getEquity() const { + return equity; +} +void +OAICurrency_portfolio::setEquity(const double &equity) { + this->equity = equity; + this->m_equity_isSet = true; +} + + +double +OAICurrency_portfolio::getBalance() const { + return balance; +} +void +OAICurrency_portfolio::setBalance(const double &balance) { + this->balance = balance; + this->m_balance_isSet = true; +} + +bool +OAICurrency_portfolio::isSet() const { + bool isObjectUpdated = false; + do{ + if(m_maintenance_margin_isSet){ isObjectUpdated = true; break;} + + if(m_available_withdrawal_funds_isSet){ isObjectUpdated = true; break;} + + if(m_initial_margin_isSet){ isObjectUpdated = true; break;} + + if(m_available_funds_isSet){ isObjectUpdated = true; break;} + + if(m_currency_isSet){ isObjectUpdated = true; break;} + + if(m_margin_balance_isSet){ isObjectUpdated = true; break;} + + if(m_equity_isSet){ isObjectUpdated = true; break;} + + if(m_balance_isSet){ isObjectUpdated = true; break;} + }while(false); + return isObjectUpdated; +} + +bool +OAICurrency_portfolio::isValid() const { + // only required properties are required for the object to be considered valid + return m_maintenance_margin_isValid && m_available_withdrawal_funds_isValid && m_initial_margin_isValid && m_available_funds_isValid && m_currency_isValid && m_margin_balance_isValid && m_equity_isValid && m_balance_isValid && true; +} + +} + diff --git a/cpp-qt5-client/client/OAICurrency_portfolio.h b/cpp-qt5-client/client/OAICurrency_portfolio.h new file mode 100644 index 0000000..26b0bb7 --- /dev/null +++ b/cpp-qt5-client/client/OAICurrency_portfolio.h @@ -0,0 +1,119 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OAICurrency_portfolio.h + * + * + */ + +#ifndef OAICurrency_portfolio_H +#define OAICurrency_portfolio_H + +#include + + +#include + +#include "OAIObject.h" +#include "OAIEnum.h" + +namespace OpenAPI { + +class OAICurrency_portfolio: public OAIObject { +public: + OAICurrency_portfolio(); + OAICurrency_portfolio(QString json); + ~OAICurrency_portfolio() override; + + QString asJson () const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + + double getMaintenanceMargin() const; + void setMaintenanceMargin(const double &maintenance_margin); + + + double getAvailableWithdrawalFunds() const; + void setAvailableWithdrawalFunds(const double &available_withdrawal_funds); + + + double getInitialMargin() const; + void setInitialMargin(const double &initial_margin); + + + double getAvailableFunds() const; + void setAvailableFunds(const double &available_funds); + + + QString getCurrency() const; + void setCurrency(const QString ¤cy); + + + double getMarginBalance() const; + void setMarginBalance(const double &margin_balance); + + + double getEquity() const; + void setEquity(const double &equity); + + + double getBalance() const; + void setBalance(const double &balance); + + + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void init(); + + double maintenance_margin; + bool m_maintenance_margin_isSet; + bool m_maintenance_margin_isValid; + + double available_withdrawal_funds; + bool m_available_withdrawal_funds_isSet; + bool m_available_withdrawal_funds_isValid; + + double initial_margin; + bool m_initial_margin_isSet; + bool m_initial_margin_isValid; + + double available_funds; + bool m_available_funds_isSet; + bool m_available_funds_isValid; + + QString currency; + bool m_currency_isSet; + bool m_currency_isValid; + + double margin_balance; + bool m_margin_balance_isSet; + bool m_margin_balance_isValid; + + double equity; + bool m_equity_isSet; + bool m_equity_isValid; + + double balance; + bool m_balance_isSet; + bool m_balance_isValid; + + }; + +} + +#endif // OAICurrency_portfolio_H diff --git a/cpp-qt5-client/client/OAICurrency_withdrawal_priorities.cpp b/cpp-qt5-client/client/OAICurrency_withdrawal_priorities.cpp new file mode 100644 index 0000000..b5d8c04 --- /dev/null +++ b/cpp-qt5-client/client/OAICurrency_withdrawal_priorities.cpp @@ -0,0 +1,127 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include "OAICurrency_withdrawal_priorities.h" + +#include "OAIHelpers.h" + +#include +#include +#include +#include + +namespace OpenAPI { + +OAICurrency_withdrawal_priorities::OAICurrency_withdrawal_priorities(QString json) { + this->init(); + this->fromJson(json); +} + +OAICurrency_withdrawal_priorities::OAICurrency_withdrawal_priorities() { + this->init(); +} + +OAICurrency_withdrawal_priorities::~OAICurrency_withdrawal_priorities() { + +} + +void +OAICurrency_withdrawal_priorities::init() { + + m_name_isSet = false; + m_name_isValid = false; + + m_value_isSet = false; + m_value_isValid = false; + } + +void +OAICurrency_withdrawal_priorities::fromJson(QString jsonString) { + QByteArray array (jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void +OAICurrency_withdrawal_priorities::fromJsonObject(QJsonObject json) { + + m_name_isValid = ::OpenAPI::fromJsonValue(name, json[QString("name")]); + + + m_value_isValid = ::OpenAPI::fromJsonValue(value, json[QString("value")]); + + +} + +QString +OAICurrency_withdrawal_priorities::asJson () const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject +OAICurrency_withdrawal_priorities::asJsonObject() const { + QJsonObject obj; + if(m_name_isSet){ + obj.insert(QString("name"), ::OpenAPI::toJsonValue(name)); + } + if(m_value_isSet){ + obj.insert(QString("value"), ::OpenAPI::toJsonValue(value)); + } + return obj; +} + + +QString +OAICurrency_withdrawal_priorities::getName() const { + return name; +} +void +OAICurrency_withdrawal_priorities::setName(const QString &name) { + this->name = name; + this->m_name_isSet = true; +} + + +double +OAICurrency_withdrawal_priorities::getValue() const { + return value; +} +void +OAICurrency_withdrawal_priorities::setValue(const double &value) { + this->value = value; + this->m_value_isSet = true; +} + +bool +OAICurrency_withdrawal_priorities::isSet() const { + bool isObjectUpdated = false; + do{ + if(m_name_isSet){ isObjectUpdated = true; break;} + + if(m_value_isSet){ isObjectUpdated = true; break;} + }while(false); + return isObjectUpdated; +} + +bool +OAICurrency_withdrawal_priorities::isValid() const { + // only required properties are required for the object to be considered valid + return m_name_isValid && m_value_isValid && true; +} + +} + diff --git a/cpp-qt5-client/client/OAICurrency_withdrawal_priorities.h b/cpp-qt5-client/client/OAICurrency_withdrawal_priorities.h new file mode 100644 index 0000000..c9e8074 --- /dev/null +++ b/cpp-qt5-client/client/OAICurrency_withdrawal_priorities.h @@ -0,0 +1,71 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OAICurrency_withdrawal_priorities.h + * + * + */ + +#ifndef OAICurrency_withdrawal_priorities_H +#define OAICurrency_withdrawal_priorities_H + +#include + + +#include + +#include "OAIObject.h" +#include "OAIEnum.h" + +namespace OpenAPI { + +class OAICurrency_withdrawal_priorities: public OAIObject { +public: + OAICurrency_withdrawal_priorities(); + OAICurrency_withdrawal_priorities(QString json); + ~OAICurrency_withdrawal_priorities() override; + + QString asJson () const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + + QString getName() const; + void setName(const QString &name); + + + double getValue() const; + void setValue(const double &value); + + + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void init(); + + QString name; + bool m_name_isSet; + bool m_name_isValid; + + double value; + bool m_value_isSet; + bool m_value_isValid; + + }; + +} + +#endif // OAICurrency_withdrawal_priorities_H diff --git a/cpp-qt5-client/client/OAIDeposit.cpp b/cpp-qt5-client/client/OAIDeposit.cpp new file mode 100644 index 0000000..b92aff1 --- /dev/null +++ b/cpp-qt5-client/client/OAIDeposit.cpp @@ -0,0 +1,237 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include "OAIDeposit.h" + +#include "OAIHelpers.h" + +#include +#include +#include +#include + +namespace OpenAPI { + +OAIDeposit::OAIDeposit(QString json) { + this->init(); + this->fromJson(json); +} + +OAIDeposit::OAIDeposit() { + this->init(); +} + +OAIDeposit::~OAIDeposit() { + +} + +void +OAIDeposit::init() { + + m_updated_timestamp_isSet = false; + m_updated_timestamp_isValid = false; + + m_state_isSet = false; + m_state_isValid = false; + + m_received_timestamp_isSet = false; + m_received_timestamp_isValid = false; + + m_currency_isSet = false; + m_currency_isValid = false; + + m_address_isSet = false; + m_address_isValid = false; + + m_amount_isSet = false; + m_amount_isValid = false; + + m_transaction_id_isSet = false; + m_transaction_id_isValid = false; + } + +void +OAIDeposit::fromJson(QString jsonString) { + QByteArray array (jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void +OAIDeposit::fromJsonObject(QJsonObject json) { + + m_updated_timestamp_isValid = ::OpenAPI::fromJsonValue(updated_timestamp, json[QString("updated_timestamp")]); + + + m_state_isValid = ::OpenAPI::fromJsonValue(state, json[QString("state")]); + + + m_received_timestamp_isValid = ::OpenAPI::fromJsonValue(received_timestamp, json[QString("received_timestamp")]); + + + m_currency_isValid = ::OpenAPI::fromJsonValue(currency, json[QString("currency")]); + + + m_address_isValid = ::OpenAPI::fromJsonValue(address, json[QString("address")]); + + + m_amount_isValid = ::OpenAPI::fromJsonValue(amount, json[QString("amount")]); + + + m_transaction_id_isValid = ::OpenAPI::fromJsonValue(transaction_id, json[QString("transaction_id")]); + + +} + +QString +OAIDeposit::asJson () const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject +OAIDeposit::asJsonObject() const { + QJsonObject obj; + if(m_updated_timestamp_isSet){ + obj.insert(QString("updated_timestamp"), ::OpenAPI::toJsonValue(updated_timestamp)); + } + if(m_state_isSet){ + obj.insert(QString("state"), ::OpenAPI::toJsonValue(state)); + } + if(m_received_timestamp_isSet){ + obj.insert(QString("received_timestamp"), ::OpenAPI::toJsonValue(received_timestamp)); + } + if(m_currency_isSet){ + obj.insert(QString("currency"), ::OpenAPI::toJsonValue(currency)); + } + if(m_address_isSet){ + obj.insert(QString("address"), ::OpenAPI::toJsonValue(address)); + } + if(m_amount_isSet){ + obj.insert(QString("amount"), ::OpenAPI::toJsonValue(amount)); + } + if(m_transaction_id_isSet){ + obj.insert(QString("transaction_id"), ::OpenAPI::toJsonValue(transaction_id)); + } + return obj; +} + + +qint32 +OAIDeposit::getUpdatedTimestamp() const { + return updated_timestamp; +} +void +OAIDeposit::setUpdatedTimestamp(const qint32 &updated_timestamp) { + this->updated_timestamp = updated_timestamp; + this->m_updated_timestamp_isSet = true; +} + + +QString +OAIDeposit::getState() const { + return state; +} +void +OAIDeposit::setState(const QString &state) { + this->state = state; + this->m_state_isSet = true; +} + + +qint32 +OAIDeposit::getReceivedTimestamp() const { + return received_timestamp; +} +void +OAIDeposit::setReceivedTimestamp(const qint32 &received_timestamp) { + this->received_timestamp = received_timestamp; + this->m_received_timestamp_isSet = true; +} + + +QString +OAIDeposit::getCurrency() const { + return currency; +} +void +OAIDeposit::setCurrency(const QString ¤cy) { + this->currency = currency; + this->m_currency_isSet = true; +} + + +QString +OAIDeposit::getAddress() const { + return address; +} +void +OAIDeposit::setAddress(const QString &address) { + this->address = address; + this->m_address_isSet = true; +} + + +double +OAIDeposit::getAmount() const { + return amount; +} +void +OAIDeposit::setAmount(const double &amount) { + this->amount = amount; + this->m_amount_isSet = true; +} + + +QString +OAIDeposit::getTransactionId() const { + return transaction_id; +} +void +OAIDeposit::setTransactionId(const QString &transaction_id) { + this->transaction_id = transaction_id; + this->m_transaction_id_isSet = true; +} + +bool +OAIDeposit::isSet() const { + bool isObjectUpdated = false; + do{ + if(m_updated_timestamp_isSet){ isObjectUpdated = true; break;} + + if(m_state_isSet){ isObjectUpdated = true; break;} + + if(m_received_timestamp_isSet){ isObjectUpdated = true; break;} + + if(m_currency_isSet){ isObjectUpdated = true; break;} + + if(m_address_isSet){ isObjectUpdated = true; break;} + + if(m_amount_isSet){ isObjectUpdated = true; break;} + + if(m_transaction_id_isSet){ isObjectUpdated = true; break;} + }while(false); + return isObjectUpdated; +} + +bool +OAIDeposit::isValid() const { + // only required properties are required for the object to be considered valid + return m_updated_timestamp_isValid && m_state_isValid && m_received_timestamp_isValid && m_currency_isValid && m_address_isValid && m_amount_isValid && m_transaction_id_isValid && true; +} + +} + diff --git a/cpp-qt5-client/client/OAIDeposit.h b/cpp-qt5-client/client/OAIDeposit.h new file mode 100644 index 0000000..6525ff8 --- /dev/null +++ b/cpp-qt5-client/client/OAIDeposit.h @@ -0,0 +1,111 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OAIDeposit.h + * + * + */ + +#ifndef OAIDeposit_H +#define OAIDeposit_H + +#include + + +#include + +#include "OAIObject.h" +#include "OAIEnum.h" + +namespace OpenAPI { + +class OAIDeposit: public OAIObject { +public: + OAIDeposit(); + OAIDeposit(QString json); + ~OAIDeposit() override; + + QString asJson () const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + + qint32 getUpdatedTimestamp() const; + void setUpdatedTimestamp(const qint32 &updated_timestamp); + + + QString getState() const; + void setState(const QString &state); + + + qint32 getReceivedTimestamp() const; + void setReceivedTimestamp(const qint32 &received_timestamp); + + + QString getCurrency() const; + void setCurrency(const QString ¤cy); + + + QString getAddress() const; + void setAddress(const QString &address); + + + double getAmount() const; + void setAmount(const double &amount); + + + QString getTransactionId() const; + void setTransactionId(const QString &transaction_id); + + + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void init(); + + qint32 updated_timestamp; + bool m_updated_timestamp_isSet; + bool m_updated_timestamp_isValid; + + QString state; + bool m_state_isSet; + bool m_state_isValid; + + qint32 received_timestamp; + bool m_received_timestamp_isSet; + bool m_received_timestamp_isValid; + + QString currency; + bool m_currency_isSet; + bool m_currency_isValid; + + QString address; + bool m_address_isSet; + bool m_address_isValid; + + double amount; + bool m_amount_isSet; + bool m_amount_isValid; + + QString transaction_id; + bool m_transaction_id_isSet; + bool m_transaction_id_isValid; + + }; + +} + +#endif // OAIDeposit_H diff --git a/cpp-qt5-client/client/OAIEnum.h b/cpp-qt5-client/client/OAIEnum.h new file mode 100644 index 0000000..2dbb1b6 --- /dev/null +++ b/cpp-qt5-client/client/OAIEnum.h @@ -0,0 +1,64 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#ifndef OAI_ENUM_H +#define OAI_ENUM_H + +#include +#include + +namespace OpenAPI { + +class OAIEnum { + public: + OAIEnum() { + + } + + OAIEnum(QString jsonString) { + fromJson(jsonString); + } + + virtual ~OAIEnum(){ + + } + + virtual QJsonValue asJsonValue() const { + return QJsonValue(jstr); + } + + virtual QString asJson() const { + return jstr; + } + + virtual void fromJson(QString jsonString) { + jstr = jsonString; + } + + virtual void fromJsonValue(QJsonValue jval) { + jstr = jval.toString(); + } + + virtual bool isSet() const { + return false; + } + + virtual bool isValid() const { + return true; + } +private : + QString jstr; +}; + +} + +#endif // OAI_ENUM_H diff --git a/cpp-qt5-client/client/OAIHelpers.cpp b/cpp-qt5-client/client/OAIHelpers.cpp new file mode 100644 index 0000000..65a3b8d --- /dev/null +++ b/cpp-qt5-client/client/OAIHelpers.cpp @@ -0,0 +1,349 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include +#include "OAIHelpers.h" + + +namespace OpenAPI { + + +QString +toStringValue(const QString &value) { + return value; +} + +QString +toStringValue(const QDateTime &value){ + // ISO 8601 + return value.toString("yyyy-MM-ddTHH:mm:ss[Z|[+|-]HH:mm]"); +} + +QString +toStringValue(const QByteArray &value){ + return QString(value); +} + +QString +toStringValue(const QDate &value){ + // ISO 8601 + return value.toString(Qt::DateFormat::ISODate); +} + +QString +toStringValue(const qint32 &value) { + return QString::number(value); +} + +QString +toStringValue(const qint64 &value) { + return QString::number(value); +} + +QString +toStringValue(const bool &value) { + return QString(value ? "true" : "false"); +} + +QString +toStringValue(const float &value){ + return QString::number(static_cast(value)); +} + +QString +toStringValue(const double &value){ + return QString::number(value); +} + +QString +toStringValue(const OAIEnum &value){ + return value.asJson(); +} + +QJsonValue +toJsonValue(const QString &value){ + return QJsonValue(value); +} + +QJsonValue +toJsonValue(const QDateTime &value){ + return QJsonValue(value.toString(Qt::ISODate)); +} + +QJsonValue +toJsonValue(const QByteArray &value){ + return QJsonValue(QString(value.toBase64())); +} + +QJsonValue +toJsonValue(const QDate &value){ + return QJsonValue(value.toString(Qt::ISODate)); +} + +QJsonValue +toJsonValue(const qint32 &value){ + return QJsonValue(value); +} + +QJsonValue +toJsonValue(const qint64 &value){ + return QJsonValue(value); +} + +QJsonValue +toJsonValue(const bool &value){ + return QJsonValue(value); +} + +QJsonValue +toJsonValue(const float &value){ + return QJsonValue(static_cast(value)); +} + +QJsonValue +toJsonValue(const double &value){ + return QJsonValue(value); +} + +QJsonValue +toJsonValue(const OAIObject &value){ + return value.asJsonObject(); +} + +QJsonValue +toJsonValue(const OAIEnum &value){ + return value.asJsonValue(); +} + +bool +fromStringValue(const QString &inStr, QString &value){ + value.clear(); + value.append(inStr); + return !inStr.isEmpty(); +} + +bool +fromStringValue(const QString &inStr, QDateTime &value){ + if(inStr.isEmpty()){ + return false; + } + else{ + auto dateTime = QDateTime::fromString(inStr, "yyyy-MM-ddTHH:mm:ss[Z|[+|-]HH:mm]"); + if(dateTime.isValid()){ + value.setDate(dateTime.date()); + value.setTime(dateTime.time()); + } + else{ + qDebug() << "DateTime is invalid"; + } + return dateTime.isValid(); + } +} + +bool +fromStringValue(const QString &inStr, QByteArray &value){ + if(inStr.isEmpty()){ + return false; + } + else{ + value.clear(); + value.append(inStr.toUtf8()); + return value.count() > 0; + } +} + +bool +fromStringValue(const QString &inStr, QDate &value){ + if(inStr.isEmpty()){ + return false; + } + else{ + auto date = QDate::fromString(inStr, Qt::DateFormat::ISODate); + if(date.isValid()){ + value.setDate(date.year(), date.month(), date.day()); + } + else{ + qDebug() << "Date is invalid"; + } + return date.isValid(); + } +} + +bool +fromStringValue(const QString &inStr, qint32 &value){ + bool ok = false; + value = QVariant(inStr).toInt(&ok); + return ok; +} + +bool +fromStringValue(const QString &inStr, qint64 &value){ + bool ok = false; + value = QVariant(inStr).toLongLong(&ok); + return ok; +} + +bool +fromStringValue(const QString &inStr, bool &value){ + value = QVariant(inStr).toBool(); + return ((inStr == "true") || (inStr == "false")); +} + +bool +fromStringValue(const QString &inStr, float &value){ + bool ok = false; + value = QVariant(inStr).toFloat(&ok); + return ok; +} + +bool +fromStringValue(const QString &inStr, double &value){ + bool ok = false; + value = QVariant(inStr).toDouble(&ok); + return ok; +} + +bool +fromStringValue(const QString &inStr, OAIEnum &value){ + value.fromJson(inStr); + return true; +} + +bool +fromJsonValue(QString &value, const QJsonValue &jval){ + bool ok = true; + if(!jval.isUndefined() && !jval.isNull()){ + if(jval.isString()){ + value = jval.toString(); + } else if(jval.isBool()) { + value = jval.toBool() ? "true" : "false"; + } else if(jval.isDouble()){ + value = QString::number(jval.toDouble()); + } else { + ok = false; + } + } else { + ok = false; + } + return ok; +} + +bool +fromJsonValue(QDateTime &value, const QJsonValue &jval){ + bool ok = true; + if(!jval.isUndefined() && !jval.isNull() && jval.isString()){ + value = QDateTime::fromString(jval.toString(), Qt::ISODate); + ok = value.isValid(); + } else { + ok = false; + } + return ok; +} + +bool +fromJsonValue(QByteArray &value, const QJsonValue &jval){ + bool ok = true; + if(!jval.isUndefined() && !jval.isNull() && jval.isString()) { + value = QByteArray::fromBase64(QByteArray::fromStdString(jval.toString().toStdString())); + ok = value.size() > 0 ; + } else { + ok = false; + } + return ok; +} + +bool +fromJsonValue(QDate &value, const QJsonValue &jval){ + bool ok = true; + if(!jval.isUndefined() && !jval.isNull() && jval.isString()){ + value = QDate::fromString(jval.toString(), Qt::ISODate); + ok = value.isValid(); + } else { + ok = false; + } + return ok; +} + +bool +fromJsonValue(qint32 &value, const QJsonValue &jval){ + bool ok = true; + if(!jval.isUndefined() && !jval.isNull() && !jval.isObject() && !jval.isArray()){ + value = jval.toInt(); + } else { + ok = false; + } + return ok; +} + +bool +fromJsonValue(qint64 &value, const QJsonValue &jval){ + bool ok = true; + if(!jval.isUndefined() && !jval.isNull() && !jval.isObject() && !jval.isArray()){ + value = jval.toVariant().toLongLong(); + } else { + ok = false; + } + return ok; +} + +bool +fromJsonValue(bool &value, const QJsonValue &jval){ + bool ok = true; + if(jval.isBool()){ + value = jval.toBool(); + } else { + ok = false; + } + return ok; +} + +bool +fromJsonValue(float &value, const QJsonValue &jval){ + bool ok = true; + if(jval.isDouble()){ + value = static_cast(jval.toDouble()); + } else { + ok = false; + } + return ok; +} + +bool +fromJsonValue(double &value, const QJsonValue &jval){ + bool ok = true; + if(jval.isDouble()){ + value = jval.toDouble(); + } else { + ok = false; + } + return ok; +} + +bool +fromJsonValue(OAIObject &value, const QJsonValue &jval){ + bool ok = true; + if(jval.isObject()){ + value.fromJsonObject(jval.toObject()); + ok = value.isValid(); + } else { + ok = false; + } + return ok; +} + +bool +fromJsonValue(OAIEnum &value, const QJsonValue &jval){ + value.fromJsonValue(jval); + return true; +} + +} diff --git a/cpp-qt5-client/client/OAIHelpers.h b/cpp-qt5-client/client/OAIHelpers.h new file mode 100644 index 0000000..5afb97f --- /dev/null +++ b/cpp-qt5-client/client/OAIHelpers.h @@ -0,0 +1,163 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#ifndef OAI_HELPERS_H +#define OAI_HELPERS_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "OAIObject.h" +#include "OAIEnum.h" + +namespace OpenAPI { + + QString toStringValue(const QString &value); + QString toStringValue(const QDateTime &value); + QString toStringValue(const QByteArray &value); + QString toStringValue(const QDate &value); + QString toStringValue(const qint32 &value); + QString toStringValue(const qint64 &value); + QString toStringValue(const bool &value); + QString toStringValue(const float &value); + QString toStringValue(const double &value); + QString toStringValue(const OAIEnum &value); + + template + QString toStringValue(const QList &val) { + QString strArray; + for(const auto& item : val) { + strArray.append(toStringValue(item) + ","); + } + if(val.count() > 0) { + strArray.chop(1); + } + return strArray; + } + + QJsonValue toJsonValue(const QString &value); + QJsonValue toJsonValue(const QDateTime &value); + QJsonValue toJsonValue(const QByteArray &value); + QJsonValue toJsonValue(const QDate &value); + QJsonValue toJsonValue(const qint32 &value); + QJsonValue toJsonValue(const qint64 &value); + QJsonValue toJsonValue(const bool &value); + QJsonValue toJsonValue(const float &value); + QJsonValue toJsonValue(const double &value); + QJsonValue toJsonValue(const OAIObject &value); + QJsonValue toJsonValue(const OAIEnum &value); + + template + QJsonValue toJsonValue(const QList &val) { + QJsonArray jArray; + for(const auto& item : val) { + jArray.append(toJsonValue(item)); + } + return jArray; + } + + template + QJsonValue toJsonValue(const QMap &val) { + QJsonObject jObject; + for(const auto& itemkey : val.keys()) { + jObject.insert(itemkey, toJsonValue(val.value(itemkey))); + } + return jObject; + } + + bool fromStringValue(const QString &inStr, QString &value); + bool fromStringValue(const QString &inStr, QDateTime &value); + bool fromStringValue(const QString &inStr, QByteArray &value); + bool fromStringValue(const QString &inStr, QDate &value); + bool fromStringValue(const QString &inStr, qint32 &value); + bool fromStringValue(const QString &inStr, qint64 &value); + bool fromStringValue(const QString &inStr, bool &value); + bool fromStringValue(const QString &inStr, float &value); + bool fromStringValue(const QString &inStr, double &value); + bool fromStringValue(const QString &inStr, OAIEnum &value); + + template + bool fromStringValue(const QList &inStr, QList &val) { + bool ok = (inStr.count() > 0); + for(const auto& item: inStr){ + T itemVal; + ok &= fromStringValue(item, itemVal); + val.push_back(itemVal); + } + return ok; + } + + template + bool fromStringValue(const QMap &inStr, QMap &val) { + bool ok = (inStr.count() > 0); + for(const auto& itemkey : inStr.keys()){ + T itemVal; + ok &= fromStringValue(inStr.value(itemkey), itemVal); + val.insert(itemkey, itemVal); + } + return ok; + } + + bool fromJsonValue(QString &value, const QJsonValue &jval); + bool fromJsonValue(QDateTime &value, const QJsonValue &jval); + bool fromJsonValue(QByteArray &value, const QJsonValue &jval); + bool fromJsonValue(QDate &value, const QJsonValue &jval); + bool fromJsonValue(qint32 &value, const QJsonValue &jval); + bool fromJsonValue(qint64 &value, const QJsonValue &jval); + bool fromJsonValue(bool &value, const QJsonValue &jval); + bool fromJsonValue(float &value, const QJsonValue &jval); + bool fromJsonValue(double &value, const QJsonValue &jval); + bool fromJsonValue(OAIObject &value, const QJsonValue &jval); + bool fromJsonValue(OAIEnum &value, const QJsonValue &jval); + + template + bool fromJsonValue(QList &val, const QJsonValue &jval) { + bool ok = true; + if(jval.isArray()){ + for(const auto& jitem : jval.toArray()){ + T item; + ok &= fromJsonValue(item, jitem); + val.push_back(item); + } + } else { + ok = false; + } + return ok; + } + + template + bool fromJsonValue(QMap &val, const QJsonValue &jval) { + bool ok = true; + if(jval.isObject()){ + auto varmap = jval.toObject().toVariantMap(); + if(varmap.count() > 0){ + for(const auto& itemkey : varmap.keys() ){ + T itemVal; + ok &= fromJsonValue(itemVal, QJsonValue::fromVariant(varmap.value(itemkey))); + val.insert(itemkey, itemVal); + } + } + } else { + ok = false; + } + return ok; + } + +} + +#endif // OAI_HELPERS_H diff --git a/cpp-qt5-client/client/OAIHttpRequest.cpp b/cpp-qt5-client/client/OAIHttpRequest.cpp new file mode 100644 index 0000000..61e85b4 --- /dev/null +++ b/cpp-qt5-client/client/OAIHttpRequest.cpp @@ -0,0 +1,333 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "OAIHttpRequest.h" +#include +#include +#include +#include +#include + + +namespace OpenAPI { + +OAIHttpRequestInput::OAIHttpRequestInput() { + initialize(); +} + +OAIHttpRequestInput::OAIHttpRequestInput(QString v_url_str, QString v_http_method) { + initialize(); + url_str = v_url_str; + http_method = v_http_method; +} + +void OAIHttpRequestInput::initialize() { + var_layout = NOT_SET; + url_str = ""; + http_method = "GET"; +} + +void OAIHttpRequestInput::add_var(QString key, QString value) { + vars[key] = value; +} + +void OAIHttpRequestInput::add_file(QString variable_name, QString local_filename, QString request_filename, QString mime_type) { + OAIHttpRequestInputFileElement file; + file.variable_name = variable_name; + file.local_filename = local_filename; + file.request_filename = request_filename; + file.mime_type = mime_type; + files.append(file); +} + + +OAIHttpRequestWorker::OAIHttpRequestWorker(QObject *parent) + : QObject(parent), manager(nullptr) +{ + qsrand(QDateTime::currentDateTime().toTime_t()); + + manager = new QNetworkAccessManager(this); + connect(manager, &QNetworkAccessManager::finished, this, &OAIHttpRequestWorker::on_manager_finished); +} + +OAIHttpRequestWorker::~OAIHttpRequestWorker() { +} + +QMap OAIHttpRequestWorker::getResponseHeaders() const { + return headers; +} + +QString OAIHttpRequestWorker::http_attribute_encode(QString attribute_name, QString input) { + // result structure follows RFC 5987 + bool need_utf_encoding = false; + QString result = ""; + QByteArray input_c = input.toLocal8Bit(); + char c; + for (int i = 0; i < input_c.length(); i++) { + c = input_c.at(i); + if (c == '\\' || c == '/' || c == '\0' || c < ' ' || c > '~') { + // ignore and request utf-8 version + need_utf_encoding = true; + } + else if (c == '"') { + result += "\\\""; + } + else { + result += c; + } + } + + if (result.length() == 0) { + need_utf_encoding = true; + } + + if (!need_utf_encoding) { + // return simple version + return QString("%1=\"%2\"").arg(attribute_name, result); + } + + QString result_utf8 = ""; + for (int i = 0; i < input_c.length(); i++) { + c = input_c.at(i); + if ( + (c >= '0' && c <= '9') + || (c >= 'A' && c <= 'Z') + || (c >= 'a' && c <= 'z') + ) { + result_utf8 += c; + } + else { + result_utf8 += "%" + QString::number(static_cast(input_c.at(i)), 16).toUpper(); + } + } + + // return enhanced version with UTF-8 support + return QString("%1=\"%2\"; %1*=utf-8''%3").arg(attribute_name, result, result_utf8); +} + +void OAIHttpRequestWorker::execute(OAIHttpRequestInput *input) { + + // reset variables + + QByteArray request_content = ""; + response = ""; + error_type = QNetworkReply::NoError; + error_str = ""; + bool isFormData = false; + + + // decide on the variable layout + + if (input->files.length() > 0) { + input->var_layout = MULTIPART; + } + if (input->var_layout == NOT_SET) { + input->var_layout = input->http_method == "GET" || input->http_method == "HEAD" ? ADDRESS : URL_ENCODED; + } + + + // prepare request content + + QString boundary = ""; + + if (input->var_layout == ADDRESS || input->var_layout == URL_ENCODED) { + // variable layout is ADDRESS or URL_ENCODED + + if (input->vars.count() > 0) { + bool first = true; + isFormData = true; + foreach (QString key, input->vars.keys()) { + if (!first) { + request_content.append("&"); + } + first = false; + + request_content.append(QUrl::toPercentEncoding(key)); + request_content.append("="); + request_content.append(QUrl::toPercentEncoding(input->vars.value(key))); + } + + if (input->var_layout == ADDRESS) { + input->url_str += "?" + request_content; + request_content = ""; + } + } + } + else { + // variable layout is MULTIPART + + boundary = "__-----------------------" + + QString::number(QDateTime::currentDateTime().toTime_t()) + + QString::number(qrand()); + QString boundary_delimiter = "--"; + QString new_line = "\r\n"; + + // add variables + foreach (QString key, input->vars.keys()) { + // add boundary + request_content.append(boundary_delimiter); + request_content.append(boundary); + request_content.append(new_line); + + // add header + request_content.append("Content-Disposition: form-data; "); + request_content.append(http_attribute_encode("name", key)); + request_content.append(new_line); + request_content.append("Content-Type: text/plain"); + request_content.append(new_line); + + // add header to body splitter + request_content.append(new_line); + + // add variable content + request_content.append(input->vars.value(key)); + request_content.append(new_line); + } + + // add files + for (QList::iterator file_info = input->files.begin(); file_info != input->files.end(); file_info++) { + QFileInfo fi(file_info->local_filename); + + // ensure necessary variables are available + if ( + file_info->local_filename == nullptr || file_info->local_filename.isEmpty() + || file_info->variable_name == nullptr || file_info->variable_name.isEmpty() + || !fi.exists() || !fi.isFile() || !fi.isReadable() + ) { + // silent abort for the current file + continue; + } + + QFile file(file_info->local_filename); + if (!file.open(QIODevice::ReadOnly)) { + // silent abort for the current file + continue; + } + + // ensure filename for the request + if (file_info->request_filename == nullptr || file_info->request_filename.isEmpty()) { + file_info->request_filename = fi.fileName(); + if (file_info->request_filename.isEmpty()) { + file_info->request_filename = "file"; + } + } + + // add boundary + request_content.append(boundary_delimiter); + request_content.append(boundary); + request_content.append(new_line); + + // add header + request_content.append(QString("Content-Disposition: form-data; %1; %2").arg( + http_attribute_encode("name", file_info->variable_name), + http_attribute_encode("filename", file_info->request_filename) + )); + request_content.append(new_line); + + if (file_info->mime_type != nullptr && !file_info->mime_type.isEmpty()) { + request_content.append("Content-Type: "); + request_content.append(file_info->mime_type); + request_content.append(new_line); + } + + request_content.append("Content-Transfer-Encoding: binary"); + request_content.append(new_line); + + // add header to body splitter + request_content.append(new_line); + + // add file content + request_content.append(file.readAll()); + request_content.append(new_line); + + file.close(); + } + + // add end of body + request_content.append(boundary_delimiter); + request_content.append(boundary); + request_content.append(boundary_delimiter); + } + + if(input->request_body.size() > 0) { + qDebug() << "got a request body"; + request_content.clear(); + request_content.append(input->request_body); + } + // prepare connection + + QNetworkRequest request = QNetworkRequest(QUrl(input->url_str)); + if (OAIHttpRequestWorker::sslDefaultConfiguration != nullptr) { + request.setSslConfiguration(*OAIHttpRequestWorker::sslDefaultConfiguration); + } + request.setRawHeader("User-Agent", "OpenAPI-Generator/1.0.0/cpp-qt5"); + foreach(QString key, input->headers.keys()) { + request.setRawHeader(key.toStdString().c_str(), input->headers.value(key).toStdString().c_str()); + } + + if (request_content.size() > 0 && !isFormData) { + request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); + } + else if (input->var_layout == URL_ENCODED) { + request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded"); + } + else if (input->var_layout == MULTIPART) { + request.setHeader(QNetworkRequest::ContentTypeHeader, "multipart/form-data; boundary=" + boundary); + } + + if (input->http_method == "GET") { + manager->get(request); + } + else if (input->http_method == "POST") { + manager->post(request, request_content); + } + else if (input->http_method == "PUT") { + manager->put(request, request_content); + } + else if (input->http_method == "HEAD") { + manager->head(request); + } + else if (input->http_method == "DELETE") { + manager->deleteResource(request); + } + else { +#if (QT_VERSION >= 0x050800) + manager->sendCustomRequest(request, input->http_method.toLatin1(), request_content); +#else + QBuffer *buffer = new QBuffer; + buffer->setData(request_content); + buffer->open(QIODevice::ReadOnly); + + QNetworkReply* reply = manager->sendCustomRequest(request, input->http_method.toLatin1(), buffer); + buffer->setParent(reply); +#endif + } + +} + +void OAIHttpRequestWorker::on_manager_finished(QNetworkReply *reply) { + error_type = reply->error(); + response = reply->readAll(); + error_str = reply->errorString(); + if(reply->rawHeaderPairs().count() > 0){ + for(const auto& item: reply->rawHeaderPairs()){ + headers.insert(item.first, item.second); + } + } + reply->deleteLater(); + + emit on_execution_finished(this); +} +QSslConfiguration* OAIHttpRequestWorker::sslDefaultConfiguration; + + +} diff --git a/cpp-qt5-client/client/OAIHttpRequest.h b/cpp-qt5-client/client/OAIHttpRequest.h new file mode 100644 index 0000000..ee82e6a --- /dev/null +++ b/cpp-qt5-client/client/OAIHttpRequest.h @@ -0,0 +1,94 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/** + * Based on http://www.creativepulse.gr/en/blog/2014/restful-api-requests-using-qt-cpp-for-linux-mac-osx-ms-windows + * By Alex Stylianos + * + **/ + +#ifndef OAI_HTTPREQUESTWORKER_H +#define OAI_HTTPREQUESTWORKER_H + +#include +#include +#include +#include +#include + + + +namespace OpenAPI { + +enum OAIHttpRequestVarLayout {NOT_SET, ADDRESS, URL_ENCODED, MULTIPART}; + +class OAIHttpRequestInputFileElement { + +public: + QString variable_name; + QString local_filename; + QString request_filename; + QString mime_type; + +}; + + +class OAIHttpRequestInput { + +public: + QString url_str; + QString http_method; + OAIHttpRequestVarLayout var_layout; + QMap vars; + QMap headers; + QList files; + QByteArray request_body; + + OAIHttpRequestInput(); + OAIHttpRequestInput(QString v_url_str, QString v_http_method); + void initialize(); + void add_var(QString key, QString value); + void add_file(QString variable_name, QString local_filename, QString request_filename, QString mime_type); + +}; + + +class OAIHttpRequestWorker : public QObject { + Q_OBJECT + +public: + QByteArray response; + QNetworkReply::NetworkError error_type; + QString error_str; + + explicit OAIHttpRequestWorker(QObject *parent = nullptr); + virtual ~OAIHttpRequestWorker(); + + QMap getResponseHeaders() const; + QString http_attribute_encode(QString attribute_name, QString input); + void execute(OAIHttpRequestInput *input); + static QSslConfiguration* sslDefaultConfiguration; + +signals: + void on_execution_finished(OAIHttpRequestWorker *worker); + +private: + QNetworkAccessManager *manager; + QMap headers; +private slots: + void on_manager_finished(QNetworkReply *reply); + +}; + +} + +#endif // OAI_HTTPREQUESTWORKER_H diff --git a/cpp-qt5-client/client/OAIInstrument.cpp b/cpp-qt5-client/client/OAIInstrument.cpp new file mode 100644 index 0000000..f050fc9 --- /dev/null +++ b/cpp-qt5-client/client/OAIInstrument.cpp @@ -0,0 +1,369 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include "OAIInstrument.h" + +#include "OAIHelpers.h" + +#include +#include +#include +#include + +namespace OpenAPI { + +OAIInstrument::OAIInstrument(QString json) { + this->init(); + this->fromJson(json); +} + +OAIInstrument::OAIInstrument() { + this->init(); +} + +OAIInstrument::~OAIInstrument() { + +} + +void +OAIInstrument::init() { + + m_quote_currency_isSet = false; + m_quote_currency_isValid = false; + + m_kind_isSet = false; + m_kind_isValid = false; + + m_tick_size_isSet = false; + m_tick_size_isValid = false; + + m_contract_size_isSet = false; + m_contract_size_isValid = false; + + m_is_active_isSet = false; + m_is_active_isValid = false; + + m_option_type_isSet = false; + m_option_type_isValid = false; + + m_min_trade_amount_isSet = false; + m_min_trade_amount_isValid = false; + + m_instrument_name_isSet = false; + m_instrument_name_isValid = false; + + m_settlement_period_isSet = false; + m_settlement_period_isValid = false; + + m_strike_isSet = false; + m_strike_isValid = false; + + m_base_currency_isSet = false; + m_base_currency_isValid = false; + + m_creation_timestamp_isSet = false; + m_creation_timestamp_isValid = false; + + m_expiration_timestamp_isSet = false; + m_expiration_timestamp_isValid = false; + } + +void +OAIInstrument::fromJson(QString jsonString) { + QByteArray array (jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void +OAIInstrument::fromJsonObject(QJsonObject json) { + + m_quote_currency_isValid = ::OpenAPI::fromJsonValue(quote_currency, json[QString("quote_currency")]); + + + m_kind_isValid = ::OpenAPI::fromJsonValue(kind, json[QString("kind")]); + + + m_tick_size_isValid = ::OpenAPI::fromJsonValue(tick_size, json[QString("tick_size")]); + + + m_contract_size_isValid = ::OpenAPI::fromJsonValue(contract_size, json[QString("contract_size")]); + + + m_is_active_isValid = ::OpenAPI::fromJsonValue(is_active, json[QString("is_active")]); + + + m_option_type_isValid = ::OpenAPI::fromJsonValue(option_type, json[QString("option_type")]); + + + m_min_trade_amount_isValid = ::OpenAPI::fromJsonValue(min_trade_amount, json[QString("min_trade_amount")]); + + + m_instrument_name_isValid = ::OpenAPI::fromJsonValue(instrument_name, json[QString("instrument_name")]); + + + m_settlement_period_isValid = ::OpenAPI::fromJsonValue(settlement_period, json[QString("settlement_period")]); + + + m_strike_isValid = ::OpenAPI::fromJsonValue(strike, json[QString("strike")]); + + + m_base_currency_isValid = ::OpenAPI::fromJsonValue(base_currency, json[QString("base_currency")]); + + + m_creation_timestamp_isValid = ::OpenAPI::fromJsonValue(creation_timestamp, json[QString("creation_timestamp")]); + + + m_expiration_timestamp_isValid = ::OpenAPI::fromJsonValue(expiration_timestamp, json[QString("expiration_timestamp")]); + + +} + +QString +OAIInstrument::asJson () const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject +OAIInstrument::asJsonObject() const { + QJsonObject obj; + if(m_quote_currency_isSet){ + obj.insert(QString("quote_currency"), ::OpenAPI::toJsonValue(quote_currency)); + } + if(m_kind_isSet){ + obj.insert(QString("kind"), ::OpenAPI::toJsonValue(kind)); + } + if(m_tick_size_isSet){ + obj.insert(QString("tick_size"), ::OpenAPI::toJsonValue(tick_size)); + } + if(m_contract_size_isSet){ + obj.insert(QString("contract_size"), ::OpenAPI::toJsonValue(contract_size)); + } + if(m_is_active_isSet){ + obj.insert(QString("is_active"), ::OpenAPI::toJsonValue(is_active)); + } + if(m_option_type_isSet){ + obj.insert(QString("option_type"), ::OpenAPI::toJsonValue(option_type)); + } + if(m_min_trade_amount_isSet){ + obj.insert(QString("min_trade_amount"), ::OpenAPI::toJsonValue(min_trade_amount)); + } + if(m_instrument_name_isSet){ + obj.insert(QString("instrument_name"), ::OpenAPI::toJsonValue(instrument_name)); + } + if(m_settlement_period_isSet){ + obj.insert(QString("settlement_period"), ::OpenAPI::toJsonValue(settlement_period)); + } + if(m_strike_isSet){ + obj.insert(QString("strike"), ::OpenAPI::toJsonValue(strike)); + } + if(m_base_currency_isSet){ + obj.insert(QString("base_currency"), ::OpenAPI::toJsonValue(base_currency)); + } + if(m_creation_timestamp_isSet){ + obj.insert(QString("creation_timestamp"), ::OpenAPI::toJsonValue(creation_timestamp)); + } + if(m_expiration_timestamp_isSet){ + obj.insert(QString("expiration_timestamp"), ::OpenAPI::toJsonValue(expiration_timestamp)); + } + return obj; +} + + +QString +OAIInstrument::getQuoteCurrency() const { + return quote_currency; +} +void +OAIInstrument::setQuoteCurrency(const QString "e_currency) { + this->quote_currency = quote_currency; + this->m_quote_currency_isSet = true; +} + + +QString +OAIInstrument::getKind() const { + return kind; +} +void +OAIInstrument::setKind(const QString &kind) { + this->kind = kind; + this->m_kind_isSet = true; +} + + +double +OAIInstrument::getTickSize() const { + return tick_size; +} +void +OAIInstrument::setTickSize(const double &tick_size) { + this->tick_size = tick_size; + this->m_tick_size_isSet = true; +} + + +qint32 +OAIInstrument::getContractSize() const { + return contract_size; +} +void +OAIInstrument::setContractSize(const qint32 &contract_size) { + this->contract_size = contract_size; + this->m_contract_size_isSet = true; +} + + +bool +OAIInstrument::isIsActive() const { + return is_active; +} +void +OAIInstrument::setIsActive(const bool &is_active) { + this->is_active = is_active; + this->m_is_active_isSet = true; +} + + +QString +OAIInstrument::getOptionType() const { + return option_type; +} +void +OAIInstrument::setOptionType(const QString &option_type) { + this->option_type = option_type; + this->m_option_type_isSet = true; +} + + +double +OAIInstrument::getMinTradeAmount() const { + return min_trade_amount; +} +void +OAIInstrument::setMinTradeAmount(const double &min_trade_amount) { + this->min_trade_amount = min_trade_amount; + this->m_min_trade_amount_isSet = true; +} + + +QString +OAIInstrument::getInstrumentName() const { + return instrument_name; +} +void +OAIInstrument::setInstrumentName(const QString &instrument_name) { + this->instrument_name = instrument_name; + this->m_instrument_name_isSet = true; +} + + +QString +OAIInstrument::getSettlementPeriod() const { + return settlement_period; +} +void +OAIInstrument::setSettlementPeriod(const QString &settlement_period) { + this->settlement_period = settlement_period; + this->m_settlement_period_isSet = true; +} + + +double +OAIInstrument::getStrike() const { + return strike; +} +void +OAIInstrument::setStrike(const double &strike) { + this->strike = strike; + this->m_strike_isSet = true; +} + + +QString +OAIInstrument::getBaseCurrency() const { + return base_currency; +} +void +OAIInstrument::setBaseCurrency(const QString &base_currency) { + this->base_currency = base_currency; + this->m_base_currency_isSet = true; +} + + +qint32 +OAIInstrument::getCreationTimestamp() const { + return creation_timestamp; +} +void +OAIInstrument::setCreationTimestamp(const qint32 &creation_timestamp) { + this->creation_timestamp = creation_timestamp; + this->m_creation_timestamp_isSet = true; +} + + +qint32 +OAIInstrument::getExpirationTimestamp() const { + return expiration_timestamp; +} +void +OAIInstrument::setExpirationTimestamp(const qint32 &expiration_timestamp) { + this->expiration_timestamp = expiration_timestamp; + this->m_expiration_timestamp_isSet = true; +} + +bool +OAIInstrument::isSet() const { + bool isObjectUpdated = false; + do{ + if(m_quote_currency_isSet){ isObjectUpdated = true; break;} + + if(m_kind_isSet){ isObjectUpdated = true; break;} + + if(m_tick_size_isSet){ isObjectUpdated = true; break;} + + if(m_contract_size_isSet){ isObjectUpdated = true; break;} + + if(m_is_active_isSet){ isObjectUpdated = true; break;} + + if(m_option_type_isSet){ isObjectUpdated = true; break;} + + if(m_min_trade_amount_isSet){ isObjectUpdated = true; break;} + + if(m_instrument_name_isSet){ isObjectUpdated = true; break;} + + if(m_settlement_period_isSet){ isObjectUpdated = true; break;} + + if(m_strike_isSet){ isObjectUpdated = true; break;} + + if(m_base_currency_isSet){ isObjectUpdated = true; break;} + + if(m_creation_timestamp_isSet){ isObjectUpdated = true; break;} + + if(m_expiration_timestamp_isSet){ isObjectUpdated = true; break;} + }while(false); + return isObjectUpdated; +} + +bool +OAIInstrument::isValid() const { + // only required properties are required for the object to be considered valid + return m_quote_currency_isValid && m_kind_isValid && m_tick_size_isValid && m_contract_size_isValid && m_is_active_isValid && m_min_trade_amount_isValid && m_instrument_name_isValid && m_settlement_period_isValid && m_base_currency_isValid && m_creation_timestamp_isValid && m_expiration_timestamp_isValid && true; +} + +} + diff --git a/cpp-qt5-client/client/OAIInstrument.h b/cpp-qt5-client/client/OAIInstrument.h new file mode 100644 index 0000000..f8efc0a --- /dev/null +++ b/cpp-qt5-client/client/OAIInstrument.h @@ -0,0 +1,159 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OAIInstrument.h + * + * + */ + +#ifndef OAIInstrument_H +#define OAIInstrument_H + +#include + + +#include + +#include "OAIObject.h" +#include "OAIEnum.h" + +namespace OpenAPI { + +class OAIInstrument: public OAIObject { +public: + OAIInstrument(); + OAIInstrument(QString json); + ~OAIInstrument() override; + + QString asJson () const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + + QString getQuoteCurrency() const; + void setQuoteCurrency(const QString "e_currency); + + + QString getKind() const; + void setKind(const QString &kind); + + + double getTickSize() const; + void setTickSize(const double &tick_size); + + + qint32 getContractSize() const; + void setContractSize(const qint32 &contract_size); + + + bool isIsActive() const; + void setIsActive(const bool &is_active); + + + QString getOptionType() const; + void setOptionType(const QString &option_type); + + + double getMinTradeAmount() const; + void setMinTradeAmount(const double &min_trade_amount); + + + QString getInstrumentName() const; + void setInstrumentName(const QString &instrument_name); + + + QString getSettlementPeriod() const; + void setSettlementPeriod(const QString &settlement_period); + + + double getStrike() const; + void setStrike(const double &strike); + + + QString getBaseCurrency() const; + void setBaseCurrency(const QString &base_currency); + + + qint32 getCreationTimestamp() const; + void setCreationTimestamp(const qint32 &creation_timestamp); + + + qint32 getExpirationTimestamp() const; + void setExpirationTimestamp(const qint32 &expiration_timestamp); + + + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void init(); + + QString quote_currency; + bool m_quote_currency_isSet; + bool m_quote_currency_isValid; + + QString kind; + bool m_kind_isSet; + bool m_kind_isValid; + + double tick_size; + bool m_tick_size_isSet; + bool m_tick_size_isValid; + + qint32 contract_size; + bool m_contract_size_isSet; + bool m_contract_size_isValid; + + bool is_active; + bool m_is_active_isSet; + bool m_is_active_isValid; + + QString option_type; + bool m_option_type_isSet; + bool m_option_type_isValid; + + double min_trade_amount; + bool m_min_trade_amount_isSet; + bool m_min_trade_amount_isValid; + + QString instrument_name; + bool m_instrument_name_isSet; + bool m_instrument_name_isValid; + + QString settlement_period; + bool m_settlement_period_isSet; + bool m_settlement_period_isValid; + + double strike; + bool m_strike_isSet; + bool m_strike_isValid; + + QString base_currency; + bool m_base_currency_isSet; + bool m_base_currency_isValid; + + qint32 creation_timestamp; + bool m_creation_timestamp_isSet; + bool m_creation_timestamp_isValid; + + qint32 expiration_timestamp; + bool m_expiration_timestamp_isSet; + bool m_expiration_timestamp_isValid; + + }; + +} + +#endif // OAIInstrument_H diff --git a/cpp-qt5-client/client/OAIInternalApi.cpp b/cpp-qt5-client/client/OAIInternalApi.cpp new file mode 100644 index 0000000..fa01354 --- /dev/null +++ b/cpp-qt5-client/client/OAIInternalApi.cpp @@ -0,0 +1,707 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "OAIInternalApi.h" +#include "OAIHelpers.h" + +#include +#include + +namespace OpenAPI { + +OAIInternalApi::OAIInternalApi() : basePath("/api/v2"), + host("www.deribit.com") { + +} + +OAIInternalApi::~OAIInternalApi() { + +} + +OAIInternalApi::OAIInternalApi(const QString& host, const QString& basePath) { + this->host = host; + this->basePath = basePath; +} + +void OAIInternalApi::setBasePath(const QString& basePath){ + this->basePath = basePath; +} + +void OAIInternalApi::setHost(const QString& host){ + this->host = host; +} + +void OAIInternalApi::addHeaders(const QString& key, const QString& value){ + defaultHeaders.insert(key, value); +} + + +void +OAIInternalApi::privateAddToAddressBookGet(const QString& currency, const QString& type, const QString& address, const QString& name, const QString& tfa) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/add_to_address_book"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("address")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(address))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("tfa")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(tfa))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIInternalApi::privateAddToAddressBookGetCallback); + + worker->execute(&input); +} + +void +OAIInternalApi::privateAddToAddressBookGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateAddToAddressBookGetSignal(output); + emit privateAddToAddressBookGetSignalFull(worker, output); + } else { + emit privateAddToAddressBookGetSignalE(output, error_type, error_str); + emit privateAddToAddressBookGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIInternalApi::privateDisableTfaWithRecoveryCodeGet(const QString& password, const QString& code) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/disable_tfa_with_recovery_code"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("password")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(password))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("code")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(code))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIInternalApi::privateDisableTfaWithRecoveryCodeGetCallback); + + worker->execute(&input); +} + +void +OAIInternalApi::privateDisableTfaWithRecoveryCodeGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateDisableTfaWithRecoveryCodeGetSignal(output); + emit privateDisableTfaWithRecoveryCodeGetSignalFull(worker, output); + } else { + emit privateDisableTfaWithRecoveryCodeGetSignalE(output, error_type, error_str); + emit privateDisableTfaWithRecoveryCodeGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIInternalApi::privateGetAddressBookGet(const QString& currency, const QString& type) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_address_book"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIInternalApi::privateGetAddressBookGetCallback); + + worker->execute(&input); +} + +void +OAIInternalApi::privateGetAddressBookGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetAddressBookGetSignal(output); + emit privateGetAddressBookGetSignalFull(worker, output); + } else { + emit privateGetAddressBookGetSignalE(output, error_type, error_str); + emit privateGetAddressBookGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIInternalApi::privateRemoveFromAddressBookGet(const QString& currency, const QString& type, const QString& address, const QString& tfa) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/remove_from_address_book"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("address")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(address))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("tfa")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(tfa))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIInternalApi::privateRemoveFromAddressBookGetCallback); + + worker->execute(&input); +} + +void +OAIInternalApi::privateRemoveFromAddressBookGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateRemoveFromAddressBookGetSignal(output); + emit privateRemoveFromAddressBookGetSignalFull(worker, output); + } else { + emit privateRemoveFromAddressBookGetSignalE(output, error_type, error_str); + emit privateRemoveFromAddressBookGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIInternalApi::privateSubmitTransferToSubaccountGet(const QString& currency, const double& amount, const qint32& destination) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/submit_transfer_to_subaccount"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("amount")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(amount))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("destination")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(destination))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIInternalApi::privateSubmitTransferToSubaccountGetCallback); + + worker->execute(&input); +} + +void +OAIInternalApi::privateSubmitTransferToSubaccountGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateSubmitTransferToSubaccountGetSignal(output); + emit privateSubmitTransferToSubaccountGetSignalFull(worker, output); + } else { + emit privateSubmitTransferToSubaccountGetSignalE(output, error_type, error_str); + emit privateSubmitTransferToSubaccountGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIInternalApi::privateSubmitTransferToUserGet(const QString& currency, const double& amount, const QString& destination, const QString& tfa) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/submit_transfer_to_user"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("amount")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(amount))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("destination")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(destination))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("tfa")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(tfa))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIInternalApi::privateSubmitTransferToUserGetCallback); + + worker->execute(&input); +} + +void +OAIInternalApi::privateSubmitTransferToUserGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateSubmitTransferToUserGetSignal(output); + emit privateSubmitTransferToUserGetSignalFull(worker, output); + } else { + emit privateSubmitTransferToUserGetSignalE(output, error_type, error_str); + emit privateSubmitTransferToUserGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIInternalApi::privateToggleDepositAddressCreationGet(const QString& currency, const bool& state) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/toggle_deposit_address_creation"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("state")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(state))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIInternalApi::privateToggleDepositAddressCreationGetCallback); + + worker->execute(&input); +} + +void +OAIInternalApi::privateToggleDepositAddressCreationGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateToggleDepositAddressCreationGetSignal(output); + emit privateToggleDepositAddressCreationGetSignalFull(worker, output); + } else { + emit privateToggleDepositAddressCreationGetSignalE(output, error_type, error_str); + emit privateToggleDepositAddressCreationGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIInternalApi::publicGetFooterGet() { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_footer"); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIInternalApi::publicGetFooterGetCallback); + + worker->execute(&input); +} + +void +OAIInternalApi::publicGetFooterGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetFooterGetSignal(output); + emit publicGetFooterGetSignalFull(worker, output); + } else { + emit publicGetFooterGetSignalE(output, error_type, error_str); + emit publicGetFooterGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIInternalApi::publicGetOptionMarkPricesGet(const QString& currency) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_option_mark_prices"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIInternalApi::publicGetOptionMarkPricesGetCallback); + + worker->execute(&input); +} + +void +OAIInternalApi::publicGetOptionMarkPricesGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetOptionMarkPricesGetSignal(output); + emit publicGetOptionMarkPricesGetSignalFull(worker, output); + } else { + emit publicGetOptionMarkPricesGetSignalE(output, error_type, error_str); + emit publicGetOptionMarkPricesGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIInternalApi::publicValidateFieldGet(const QString& field, const QString& value, const QString& value2) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/validate_field"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("field")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(field))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("value")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(value))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("value2")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(value2))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIInternalApi::publicValidateFieldGetCallback); + + worker->execute(&input); +} + +void +OAIInternalApi::publicValidateFieldGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicValidateFieldGetSignal(output); + emit publicValidateFieldGetSignalFull(worker, output); + } else { + emit publicValidateFieldGetSignalE(output, error_type, error_str); + emit publicValidateFieldGetSignalEFull(worker, error_type, error_str); + } +} + + +} diff --git a/cpp-qt5-client/client/OAIInternalApi.h b/cpp-qt5-client/client/OAIInternalApi.h new file mode 100644 index 0000000..1c72c35 --- /dev/null +++ b/cpp-qt5-client/client/OAIInternalApi.h @@ -0,0 +1,111 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#ifndef OAI_OAIInternalApi_H +#define OAI_OAIInternalApi_H + +#include "OAIHttpRequest.h" + +#include "OAIObject.h" +#include + +#include + +namespace OpenAPI { + +class OAIInternalApi: public QObject { + Q_OBJECT + +public: + OAIInternalApi(); + OAIInternalApi(const QString& host, const QString& basePath); + ~OAIInternalApi(); + + void setBasePath(const QString& basePath); + void setHost(const QString& host); + void addHeaders(const QString& key, const QString& value); + + void privateAddToAddressBookGet(const QString& currency, const QString& type, const QString& address, const QString& name, const QString& tfa); + void privateDisableTfaWithRecoveryCodeGet(const QString& password, const QString& code); + void privateGetAddressBookGet(const QString& currency, const QString& type); + void privateRemoveFromAddressBookGet(const QString& currency, const QString& type, const QString& address, const QString& tfa); + void privateSubmitTransferToSubaccountGet(const QString& currency, const double& amount, const qint32& destination); + void privateSubmitTransferToUserGet(const QString& currency, const double& amount, const QString& destination, const QString& tfa); + void privateToggleDepositAddressCreationGet(const QString& currency, const bool& state); + void publicGetFooterGet(); + void publicGetOptionMarkPricesGet(const QString& currency); + void publicValidateFieldGet(const QString& field, const QString& value, const QString& value2); + +private: + QString basePath; + QString host; + QMap defaultHeaders; + void privateAddToAddressBookGetCallback (OAIHttpRequestWorker * worker); + void privateDisableTfaWithRecoveryCodeGetCallback (OAIHttpRequestWorker * worker); + void privateGetAddressBookGetCallback (OAIHttpRequestWorker * worker); + void privateRemoveFromAddressBookGetCallback (OAIHttpRequestWorker * worker); + void privateSubmitTransferToSubaccountGetCallback (OAIHttpRequestWorker * worker); + void privateSubmitTransferToUserGetCallback (OAIHttpRequestWorker * worker); + void privateToggleDepositAddressCreationGetCallback (OAIHttpRequestWorker * worker); + void publicGetFooterGetCallback (OAIHttpRequestWorker * worker); + void publicGetOptionMarkPricesGetCallback (OAIHttpRequestWorker * worker); + void publicValidateFieldGetCallback (OAIHttpRequestWorker * worker); + +signals: + void privateAddToAddressBookGetSignal(OAIObject summary); + void privateDisableTfaWithRecoveryCodeGetSignal(OAIObject summary); + void privateGetAddressBookGetSignal(OAIObject summary); + void privateRemoveFromAddressBookGetSignal(OAIObject summary); + void privateSubmitTransferToSubaccountGetSignal(OAIObject summary); + void privateSubmitTransferToUserGetSignal(OAIObject summary); + void privateToggleDepositAddressCreationGetSignal(OAIObject summary); + void publicGetFooterGetSignal(OAIObject summary); + void publicGetOptionMarkPricesGetSignal(OAIObject summary); + void publicValidateFieldGetSignal(OAIObject summary); + + void privateAddToAddressBookGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateDisableTfaWithRecoveryCodeGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetAddressBookGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateRemoveFromAddressBookGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateSubmitTransferToSubaccountGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateSubmitTransferToUserGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateToggleDepositAddressCreationGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetFooterGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetOptionMarkPricesGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicValidateFieldGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + + void privateAddToAddressBookGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateDisableTfaWithRecoveryCodeGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetAddressBookGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateRemoveFromAddressBookGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSubmitTransferToSubaccountGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSubmitTransferToUserGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateToggleDepositAddressCreationGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetFooterGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetOptionMarkPricesGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicValidateFieldGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + + void privateAddToAddressBookGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateDisableTfaWithRecoveryCodeGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetAddressBookGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateRemoveFromAddressBookGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSubmitTransferToSubaccountGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSubmitTransferToUserGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateToggleDepositAddressCreationGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetFooterGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetOptionMarkPricesGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicValidateFieldGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + +}; + +} +#endif diff --git a/cpp-qt5-client/client/OAIKey_number_pair.cpp b/cpp-qt5-client/client/OAIKey_number_pair.cpp new file mode 100644 index 0000000..e98bb28 --- /dev/null +++ b/cpp-qt5-client/client/OAIKey_number_pair.cpp @@ -0,0 +1,127 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include "OAIKey_number_pair.h" + +#include "OAIHelpers.h" + +#include +#include +#include +#include + +namespace OpenAPI { + +OAIKey_number_pair::OAIKey_number_pair(QString json) { + this->init(); + this->fromJson(json); +} + +OAIKey_number_pair::OAIKey_number_pair() { + this->init(); +} + +OAIKey_number_pair::~OAIKey_number_pair() { + +} + +void +OAIKey_number_pair::init() { + + m_name_isSet = false; + m_name_isValid = false; + + m_value_isSet = false; + m_value_isValid = false; + } + +void +OAIKey_number_pair::fromJson(QString jsonString) { + QByteArray array (jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void +OAIKey_number_pair::fromJsonObject(QJsonObject json) { + + m_name_isValid = ::OpenAPI::fromJsonValue(name, json[QString("name")]); + + + m_value_isValid = ::OpenAPI::fromJsonValue(value, json[QString("value")]); + + +} + +QString +OAIKey_number_pair::asJson () const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject +OAIKey_number_pair::asJsonObject() const { + QJsonObject obj; + if(m_name_isSet){ + obj.insert(QString("name"), ::OpenAPI::toJsonValue(name)); + } + if(m_value_isSet){ + obj.insert(QString("value"), ::OpenAPI::toJsonValue(value)); + } + return obj; +} + + +QString +OAIKey_number_pair::getName() const { + return name; +} +void +OAIKey_number_pair::setName(const QString &name) { + this->name = name; + this->m_name_isSet = true; +} + + +double +OAIKey_number_pair::getValue() const { + return value; +} +void +OAIKey_number_pair::setValue(const double &value) { + this->value = value; + this->m_value_isSet = true; +} + +bool +OAIKey_number_pair::isSet() const { + bool isObjectUpdated = false; + do{ + if(m_name_isSet){ isObjectUpdated = true; break;} + + if(m_value_isSet){ isObjectUpdated = true; break;} + }while(false); + return isObjectUpdated; +} + +bool +OAIKey_number_pair::isValid() const { + // only required properties are required for the object to be considered valid + return m_name_isValid && m_value_isValid && true; +} + +} + diff --git a/cpp-qt5-client/client/OAIKey_number_pair.h b/cpp-qt5-client/client/OAIKey_number_pair.h new file mode 100644 index 0000000..6867038 --- /dev/null +++ b/cpp-qt5-client/client/OAIKey_number_pair.h @@ -0,0 +1,71 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OAIKey_number_pair.h + * + * + */ + +#ifndef OAIKey_number_pair_H +#define OAIKey_number_pair_H + +#include + + +#include + +#include "OAIObject.h" +#include "OAIEnum.h" + +namespace OpenAPI { + +class OAIKey_number_pair: public OAIObject { +public: + OAIKey_number_pair(); + OAIKey_number_pair(QString json); + ~OAIKey_number_pair() override; + + QString asJson () const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + + QString getName() const; + void setName(const QString &name); + + + double getValue() const; + void setValue(const double &value); + + + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void init(); + + QString name; + bool m_name_isSet; + bool m_name_isValid; + + double value; + bool m_value_isSet; + bool m_value_isValid; + + }; + +} + +#endif // OAIKey_number_pair_H diff --git a/cpp-qt5-client/client/OAIMarketDataApi.cpp b/cpp-qt5-client/client/OAIMarketDataApi.cpp new file mode 100644 index 0000000..49394b2 --- /dev/null +++ b/cpp-qt5-client/client/OAIMarketDataApi.cpp @@ -0,0 +1,1283 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "OAIMarketDataApi.h" +#include "OAIHelpers.h" + +#include +#include + +namespace OpenAPI { + +OAIMarketDataApi::OAIMarketDataApi() : basePath("/api/v2"), + host("www.deribit.com") { + +} + +OAIMarketDataApi::~OAIMarketDataApi() { + +} + +OAIMarketDataApi::OAIMarketDataApi(const QString& host, const QString& basePath) { + this->host = host; + this->basePath = basePath; +} + +void OAIMarketDataApi::setBasePath(const QString& basePath){ + this->basePath = basePath; +} + +void OAIMarketDataApi::setHost(const QString& host){ + this->host = host; +} + +void OAIMarketDataApi::addHeaders(const QString& key, const QString& value){ + defaultHeaders.insert(key, value); +} + + +void +OAIMarketDataApi::publicGetBookSummaryByCurrencyGet(const QString& currency, const QString& kind) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_book_summary_by_currency"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("kind")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(kind))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIMarketDataApi::publicGetBookSummaryByCurrencyGetCallback); + + worker->execute(&input); +} + +void +OAIMarketDataApi::publicGetBookSummaryByCurrencyGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetBookSummaryByCurrencyGetSignal(output); + emit publicGetBookSummaryByCurrencyGetSignalFull(worker, output); + } else { + emit publicGetBookSummaryByCurrencyGetSignalE(output, error_type, error_str); + emit publicGetBookSummaryByCurrencyGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIMarketDataApi::publicGetBookSummaryByInstrumentGet(const QString& instrument_name) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_book_summary_by_instrument"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIMarketDataApi::publicGetBookSummaryByInstrumentGetCallback); + + worker->execute(&input); +} + +void +OAIMarketDataApi::publicGetBookSummaryByInstrumentGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetBookSummaryByInstrumentGetSignal(output); + emit publicGetBookSummaryByInstrumentGetSignalFull(worker, output); + } else { + emit publicGetBookSummaryByInstrumentGetSignalE(output, error_type, error_str); + emit publicGetBookSummaryByInstrumentGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIMarketDataApi::publicGetContractSizeGet(const QString& instrument_name) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_contract_size"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIMarketDataApi::publicGetContractSizeGetCallback); + + worker->execute(&input); +} + +void +OAIMarketDataApi::publicGetContractSizeGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetContractSizeGetSignal(output); + emit publicGetContractSizeGetSignalFull(worker, output); + } else { + emit publicGetContractSizeGetSignalE(output, error_type, error_str); + emit publicGetContractSizeGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIMarketDataApi::publicGetCurrenciesGet() { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_currencies"); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIMarketDataApi::publicGetCurrenciesGetCallback); + + worker->execute(&input); +} + +void +OAIMarketDataApi::publicGetCurrenciesGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetCurrenciesGetSignal(output); + emit publicGetCurrenciesGetSignalFull(worker, output); + } else { + emit publicGetCurrenciesGetSignalE(output, error_type, error_str); + emit publicGetCurrenciesGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIMarketDataApi::publicGetFundingChartDataGet(const QString& instrument_name, const QString& length) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_funding_chart_data"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("length")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(length))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIMarketDataApi::publicGetFundingChartDataGetCallback); + + worker->execute(&input); +} + +void +OAIMarketDataApi::publicGetFundingChartDataGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetFundingChartDataGetSignal(output); + emit publicGetFundingChartDataGetSignalFull(worker, output); + } else { + emit publicGetFundingChartDataGetSignalE(output, error_type, error_str); + emit publicGetFundingChartDataGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIMarketDataApi::publicGetHistoricalVolatilityGet(const QString& currency) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_historical_volatility"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIMarketDataApi::publicGetHistoricalVolatilityGetCallback); + + worker->execute(&input); +} + +void +OAIMarketDataApi::publicGetHistoricalVolatilityGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetHistoricalVolatilityGetSignal(output); + emit publicGetHistoricalVolatilityGetSignalFull(worker, output); + } else { + emit publicGetHistoricalVolatilityGetSignalE(output, error_type, error_str); + emit publicGetHistoricalVolatilityGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIMarketDataApi::publicGetIndexGet(const QString& currency) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_index"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIMarketDataApi::publicGetIndexGetCallback); + + worker->execute(&input); +} + +void +OAIMarketDataApi::publicGetIndexGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetIndexGetSignal(output); + emit publicGetIndexGetSignalFull(worker, output); + } else { + emit publicGetIndexGetSignalE(output, error_type, error_str); + emit publicGetIndexGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIMarketDataApi::publicGetInstrumentsGet(const QString& currency, const QString& kind, const bool& expired) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_instruments"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("kind")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(kind))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("expired")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(expired))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIMarketDataApi::publicGetInstrumentsGetCallback); + + worker->execute(&input); +} + +void +OAIMarketDataApi::publicGetInstrumentsGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetInstrumentsGetSignal(output); + emit publicGetInstrumentsGetSignalFull(worker, output); + } else { + emit publicGetInstrumentsGetSignalE(output, error_type, error_str); + emit publicGetInstrumentsGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIMarketDataApi::publicGetLastSettlementsByCurrencyGet(const QString& currency, const QString& type, const qint32& count, const QString& continuation, const qint32& search_start_timestamp) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_last_settlements_by_currency"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("continuation")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(continuation))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("search_start_timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(search_start_timestamp))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIMarketDataApi::publicGetLastSettlementsByCurrencyGetCallback); + + worker->execute(&input); +} + +void +OAIMarketDataApi::publicGetLastSettlementsByCurrencyGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetLastSettlementsByCurrencyGetSignal(output); + emit publicGetLastSettlementsByCurrencyGetSignalFull(worker, output); + } else { + emit publicGetLastSettlementsByCurrencyGetSignalE(output, error_type, error_str); + emit publicGetLastSettlementsByCurrencyGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIMarketDataApi::publicGetLastSettlementsByInstrumentGet(const QString& instrument_name, const QString& type, const qint32& count, const QString& continuation, const qint32& search_start_timestamp) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_last_settlements_by_instrument"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("continuation")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(continuation))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("search_start_timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(search_start_timestamp))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIMarketDataApi::publicGetLastSettlementsByInstrumentGetCallback); + + worker->execute(&input); +} + +void +OAIMarketDataApi::publicGetLastSettlementsByInstrumentGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetLastSettlementsByInstrumentGetSignal(output); + emit publicGetLastSettlementsByInstrumentGetSignalFull(worker, output); + } else { + emit publicGetLastSettlementsByInstrumentGetSignalE(output, error_type, error_str); + emit publicGetLastSettlementsByInstrumentGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIMarketDataApi::publicGetLastTradesByCurrencyAndTimeGet(const QString& currency, const qint32& start_timestamp, const qint32& end_timestamp, const QString& kind, const qint32& count, const bool& include_old, const QString& sorting) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_last_trades_by_currency_and_time"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("kind")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(kind))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("start_timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(start_timestamp))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("end_timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(end_timestamp))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("include_old")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(include_old))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sorting")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sorting))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIMarketDataApi::publicGetLastTradesByCurrencyAndTimeGetCallback); + + worker->execute(&input); +} + +void +OAIMarketDataApi::publicGetLastTradesByCurrencyAndTimeGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetLastTradesByCurrencyAndTimeGetSignal(output); + emit publicGetLastTradesByCurrencyAndTimeGetSignalFull(worker, output); + } else { + emit publicGetLastTradesByCurrencyAndTimeGetSignalE(output, error_type, error_str); + emit publicGetLastTradesByCurrencyAndTimeGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIMarketDataApi::publicGetLastTradesByCurrencyGet(const QString& currency, const QString& kind, const QString& start_id, const QString& end_id, const qint32& count, const bool& include_old, const QString& sorting) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_last_trades_by_currency"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("kind")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(kind))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("start_id")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(start_id))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("end_id")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(end_id))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("include_old")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(include_old))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sorting")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sorting))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIMarketDataApi::publicGetLastTradesByCurrencyGetCallback); + + worker->execute(&input); +} + +void +OAIMarketDataApi::publicGetLastTradesByCurrencyGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetLastTradesByCurrencyGetSignal(output); + emit publicGetLastTradesByCurrencyGetSignalFull(worker, output); + } else { + emit publicGetLastTradesByCurrencyGetSignalE(output, error_type, error_str); + emit publicGetLastTradesByCurrencyGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIMarketDataApi::publicGetLastTradesByInstrumentAndTimeGet(const QString& instrument_name, const qint32& start_timestamp, const qint32& end_timestamp, const qint32& count, const bool& include_old, const QString& sorting) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_last_trades_by_instrument_and_time"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("start_timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(start_timestamp))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("end_timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(end_timestamp))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("include_old")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(include_old))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sorting")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sorting))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIMarketDataApi::publicGetLastTradesByInstrumentAndTimeGetCallback); + + worker->execute(&input); +} + +void +OAIMarketDataApi::publicGetLastTradesByInstrumentAndTimeGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetLastTradesByInstrumentAndTimeGetSignal(output); + emit publicGetLastTradesByInstrumentAndTimeGetSignalFull(worker, output); + } else { + emit publicGetLastTradesByInstrumentAndTimeGetSignalE(output, error_type, error_str); + emit publicGetLastTradesByInstrumentAndTimeGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIMarketDataApi::publicGetLastTradesByInstrumentGet(const QString& instrument_name, const qint32& start_seq, const qint32& end_seq, const qint32& count, const bool& include_old, const QString& sorting) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_last_trades_by_instrument"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("start_seq")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(start_seq))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("end_seq")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(end_seq))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("include_old")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(include_old))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sorting")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sorting))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIMarketDataApi::publicGetLastTradesByInstrumentGetCallback); + + worker->execute(&input); +} + +void +OAIMarketDataApi::publicGetLastTradesByInstrumentGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetLastTradesByInstrumentGetSignal(output); + emit publicGetLastTradesByInstrumentGetSignalFull(worker, output); + } else { + emit publicGetLastTradesByInstrumentGetSignalE(output, error_type, error_str); + emit publicGetLastTradesByInstrumentGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIMarketDataApi::publicGetOrderBookGet(const QString& instrument_name, const double& depth) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_order_book"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("depth")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(depth))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIMarketDataApi::publicGetOrderBookGetCallback); + + worker->execute(&input); +} + +void +OAIMarketDataApi::publicGetOrderBookGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetOrderBookGetSignal(output); + emit publicGetOrderBookGetSignalFull(worker, output); + } else { + emit publicGetOrderBookGetSignalE(output, error_type, error_str); + emit publicGetOrderBookGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIMarketDataApi::publicGetTradeVolumesGet() { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_trade_volumes"); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIMarketDataApi::publicGetTradeVolumesGetCallback); + + worker->execute(&input); +} + +void +OAIMarketDataApi::publicGetTradeVolumesGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetTradeVolumesGetSignal(output); + emit publicGetTradeVolumesGetSignalFull(worker, output); + } else { + emit publicGetTradeVolumesGetSignalE(output, error_type, error_str); + emit publicGetTradeVolumesGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIMarketDataApi::publicGetTradingviewChartDataGet(const QString& instrument_name, const qint32& start_timestamp, const qint32& end_timestamp) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_tradingview_chart_data"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("start_timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(start_timestamp))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("end_timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(end_timestamp))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIMarketDataApi::publicGetTradingviewChartDataGetCallback); + + worker->execute(&input); +} + +void +OAIMarketDataApi::publicGetTradingviewChartDataGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetTradingviewChartDataGetSignal(output); + emit publicGetTradingviewChartDataGetSignalFull(worker, output); + } else { + emit publicGetTradingviewChartDataGetSignalE(output, error_type, error_str); + emit publicGetTradingviewChartDataGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIMarketDataApi::publicTickerGet(const QString& instrument_name) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/ticker"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIMarketDataApi::publicTickerGetCallback); + + worker->execute(&input); +} + +void +OAIMarketDataApi::publicTickerGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicTickerGetSignal(output); + emit publicTickerGetSignalFull(worker, output); + } else { + emit publicTickerGetSignalE(output, error_type, error_str); + emit publicTickerGetSignalEFull(worker, error_type, error_str); + } +} + + +} diff --git a/cpp-qt5-client/client/OAIMarketDataApi.h b/cpp-qt5-client/client/OAIMarketDataApi.h new file mode 100644 index 0000000..520fc47 --- /dev/null +++ b/cpp-qt5-client/client/OAIMarketDataApi.h @@ -0,0 +1,159 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#ifndef OAI_OAIMarketDataApi_H +#define OAI_OAIMarketDataApi_H + +#include "OAIHttpRequest.h" + +#include "OAIObject.h" +#include + +#include + +namespace OpenAPI { + +class OAIMarketDataApi: public QObject { + Q_OBJECT + +public: + OAIMarketDataApi(); + OAIMarketDataApi(const QString& host, const QString& basePath); + ~OAIMarketDataApi(); + + void setBasePath(const QString& basePath); + void setHost(const QString& host); + void addHeaders(const QString& key, const QString& value); + + void publicGetBookSummaryByCurrencyGet(const QString& currency, const QString& kind); + void publicGetBookSummaryByInstrumentGet(const QString& instrument_name); + void publicGetContractSizeGet(const QString& instrument_name); + void publicGetCurrenciesGet(); + void publicGetFundingChartDataGet(const QString& instrument_name, const QString& length); + void publicGetHistoricalVolatilityGet(const QString& currency); + void publicGetIndexGet(const QString& currency); + void publicGetInstrumentsGet(const QString& currency, const QString& kind, const bool& expired); + void publicGetLastSettlementsByCurrencyGet(const QString& currency, const QString& type, const qint32& count, const QString& continuation, const qint32& search_start_timestamp); + void publicGetLastSettlementsByInstrumentGet(const QString& instrument_name, const QString& type, const qint32& count, const QString& continuation, const qint32& search_start_timestamp); + void publicGetLastTradesByCurrencyAndTimeGet(const QString& currency, const qint32& start_timestamp, const qint32& end_timestamp, const QString& kind, const qint32& count, const bool& include_old, const QString& sorting); + void publicGetLastTradesByCurrencyGet(const QString& currency, const QString& kind, const QString& start_id, const QString& end_id, const qint32& count, const bool& include_old, const QString& sorting); + void publicGetLastTradesByInstrumentAndTimeGet(const QString& instrument_name, const qint32& start_timestamp, const qint32& end_timestamp, const qint32& count, const bool& include_old, const QString& sorting); + void publicGetLastTradesByInstrumentGet(const QString& instrument_name, const qint32& start_seq, const qint32& end_seq, const qint32& count, const bool& include_old, const QString& sorting); + void publicGetOrderBookGet(const QString& instrument_name, const double& depth); + void publicGetTradeVolumesGet(); + void publicGetTradingviewChartDataGet(const QString& instrument_name, const qint32& start_timestamp, const qint32& end_timestamp); + void publicTickerGet(const QString& instrument_name); + +private: + QString basePath; + QString host; + QMap defaultHeaders; + void publicGetBookSummaryByCurrencyGetCallback (OAIHttpRequestWorker * worker); + void publicGetBookSummaryByInstrumentGetCallback (OAIHttpRequestWorker * worker); + void publicGetContractSizeGetCallback (OAIHttpRequestWorker * worker); + void publicGetCurrenciesGetCallback (OAIHttpRequestWorker * worker); + void publicGetFundingChartDataGetCallback (OAIHttpRequestWorker * worker); + void publicGetHistoricalVolatilityGetCallback (OAIHttpRequestWorker * worker); + void publicGetIndexGetCallback (OAIHttpRequestWorker * worker); + void publicGetInstrumentsGetCallback (OAIHttpRequestWorker * worker); + void publicGetLastSettlementsByCurrencyGetCallback (OAIHttpRequestWorker * worker); + void publicGetLastSettlementsByInstrumentGetCallback (OAIHttpRequestWorker * worker); + void publicGetLastTradesByCurrencyAndTimeGetCallback (OAIHttpRequestWorker * worker); + void publicGetLastTradesByCurrencyGetCallback (OAIHttpRequestWorker * worker); + void publicGetLastTradesByInstrumentAndTimeGetCallback (OAIHttpRequestWorker * worker); + void publicGetLastTradesByInstrumentGetCallback (OAIHttpRequestWorker * worker); + void publicGetOrderBookGetCallback (OAIHttpRequestWorker * worker); + void publicGetTradeVolumesGetCallback (OAIHttpRequestWorker * worker); + void publicGetTradingviewChartDataGetCallback (OAIHttpRequestWorker * worker); + void publicTickerGetCallback (OAIHttpRequestWorker * worker); + +signals: + void publicGetBookSummaryByCurrencyGetSignal(OAIObject summary); + void publicGetBookSummaryByInstrumentGetSignal(OAIObject summary); + void publicGetContractSizeGetSignal(OAIObject summary); + void publicGetCurrenciesGetSignal(OAIObject summary); + void publicGetFundingChartDataGetSignal(OAIObject summary); + void publicGetHistoricalVolatilityGetSignal(OAIObject summary); + void publicGetIndexGetSignal(OAIObject summary); + void publicGetInstrumentsGetSignal(OAIObject summary); + void publicGetLastSettlementsByCurrencyGetSignal(OAIObject summary); + void publicGetLastSettlementsByInstrumentGetSignal(OAIObject summary); + void publicGetLastTradesByCurrencyAndTimeGetSignal(OAIObject summary); + void publicGetLastTradesByCurrencyGetSignal(OAIObject summary); + void publicGetLastTradesByInstrumentAndTimeGetSignal(OAIObject summary); + void publicGetLastTradesByInstrumentGetSignal(OAIObject summary); + void publicGetOrderBookGetSignal(OAIObject summary); + void publicGetTradeVolumesGetSignal(OAIObject summary); + void publicGetTradingviewChartDataGetSignal(OAIObject summary); + void publicTickerGetSignal(OAIObject summary); + + void publicGetBookSummaryByCurrencyGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetBookSummaryByInstrumentGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetContractSizeGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetCurrenciesGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetFundingChartDataGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetHistoricalVolatilityGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetIndexGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetInstrumentsGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetLastSettlementsByCurrencyGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetLastSettlementsByInstrumentGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetLastTradesByCurrencyAndTimeGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetLastTradesByCurrencyGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetLastTradesByInstrumentAndTimeGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetLastTradesByInstrumentGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetOrderBookGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetTradeVolumesGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetTradingviewChartDataGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicTickerGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + + void publicGetBookSummaryByCurrencyGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetBookSummaryByInstrumentGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetContractSizeGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetCurrenciesGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetFundingChartDataGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetHistoricalVolatilityGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetIndexGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetInstrumentsGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetLastSettlementsByCurrencyGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetLastSettlementsByInstrumentGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetLastTradesByCurrencyAndTimeGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetLastTradesByCurrencyGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetLastTradesByInstrumentAndTimeGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetLastTradesByInstrumentGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetOrderBookGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetTradeVolumesGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetTradingviewChartDataGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicTickerGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + + void publicGetBookSummaryByCurrencyGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetBookSummaryByInstrumentGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetContractSizeGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetCurrenciesGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetFundingChartDataGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetHistoricalVolatilityGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetIndexGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetInstrumentsGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetLastSettlementsByCurrencyGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetLastSettlementsByInstrumentGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetLastTradesByCurrencyAndTimeGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetLastTradesByCurrencyGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetLastTradesByInstrumentAndTimeGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetLastTradesByInstrumentGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetOrderBookGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetTradeVolumesGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetTradingviewChartDataGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicTickerGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + +}; + +} +#endif diff --git a/cpp-qt5-client/client/OAIObject.h b/cpp-qt5-client/client/OAIObject.h new file mode 100644 index 0000000..35210c2 --- /dev/null +++ b/cpp-qt5-client/client/OAIObject.h @@ -0,0 +1,66 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#ifndef OAI_OBJECT_H +#define OAI_OBJECT_H + +#include +#include + +namespace OpenAPI { + +class OAIObject { + public: + OAIObject() { + + } + + OAIObject(QString jsonString) { + fromJson(jsonString); + } + + virtual ~OAIObject(){ + + } + + virtual QJsonObject asJsonObject() const { + return jObj; + } + + virtual QString asJson() const { + QJsonDocument doc(jObj); + return doc.toJson(QJsonDocument::Compact); + } + + virtual void fromJson(QString jsonString) { + QJsonDocument doc = QJsonDocument::fromJson(jsonString.toUtf8()); + jObj = doc.object(); + } + + virtual void fromJsonObject(QJsonObject json) { + jObj = json; + } + + virtual bool isSet() const { + return false; + } + + virtual bool isValid() const { + return true; + } +private : + QJsonObject jObj; +}; + +} + +#endif // OAI_OBJECT_H diff --git a/cpp-qt5-client/client/OAIOrder.cpp b/cpp-qt5-client/client/OAIOrder.cpp new file mode 100644 index 0000000..e1713f4 --- /dev/null +++ b/cpp-qt5-client/client/OAIOrder.cpp @@ -0,0 +1,677 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include "OAIOrder.h" + +#include "OAIHelpers.h" + +#include +#include +#include +#include + +namespace OpenAPI { + +OAIOrder::OAIOrder(QString json) { + this->init(); + this->fromJson(json); +} + +OAIOrder::OAIOrder() { + this->init(); +} + +OAIOrder::~OAIOrder() { + +} + +void +OAIOrder::init() { + + m_direction_isSet = false; + m_direction_isValid = false; + + m_reduce_only_isSet = false; + m_reduce_only_isValid = false; + + m_triggered_isSet = false; + m_triggered_isValid = false; + + m_order_id_isSet = false; + m_order_id_isValid = false; + + m_price_isSet = false; + m_price_isValid = false; + + m_time_in_force_isSet = false; + m_time_in_force_isValid = false; + + m_api_isSet = false; + m_api_isValid = false; + + m_order_state_isSet = false; + m_order_state_isValid = false; + + m_implv_isSet = false; + m_implv_isValid = false; + + m_advanced_isSet = false; + m_advanced_isValid = false; + + m_post_only_isSet = false; + m_post_only_isValid = false; + + m_usd_isSet = false; + m_usd_isValid = false; + + m_stop_price_isSet = false; + m_stop_price_isValid = false; + + m_order_type_isSet = false; + m_order_type_isValid = false; + + m_last_update_timestamp_isSet = false; + m_last_update_timestamp_isValid = false; + + m_original_order_type_isSet = false; + m_original_order_type_isValid = false; + + m_max_show_isSet = false; + m_max_show_isValid = false; + + m_profit_loss_isSet = false; + m_profit_loss_isValid = false; + + m_is_liquidation_isSet = false; + m_is_liquidation_isValid = false; + + m_filled_amount_isSet = false; + m_filled_amount_isValid = false; + + m_label_isSet = false; + m_label_isValid = false; + + m_commission_isSet = false; + m_commission_isValid = false; + + m_amount_isSet = false; + m_amount_isValid = false; + + m_trigger_isSet = false; + m_trigger_isValid = false; + + m_instrument_name_isSet = false; + m_instrument_name_isValid = false; + + m_creation_timestamp_isSet = false; + m_creation_timestamp_isValid = false; + + m_average_price_isSet = false; + m_average_price_isValid = false; + } + +void +OAIOrder::fromJson(QString jsonString) { + QByteArray array (jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void +OAIOrder::fromJsonObject(QJsonObject json) { + + m_direction_isValid = ::OpenAPI::fromJsonValue(direction, json[QString("direction")]); + + + m_reduce_only_isValid = ::OpenAPI::fromJsonValue(reduce_only, json[QString("reduce_only")]); + + + m_triggered_isValid = ::OpenAPI::fromJsonValue(triggered, json[QString("triggered")]); + + + m_order_id_isValid = ::OpenAPI::fromJsonValue(order_id, json[QString("order_id")]); + + + m_price_isValid = ::OpenAPI::fromJsonValue(price, json[QString("price")]); + + + m_time_in_force_isValid = ::OpenAPI::fromJsonValue(time_in_force, json[QString("time_in_force")]); + + + m_api_isValid = ::OpenAPI::fromJsonValue(api, json[QString("api")]); + + + m_order_state_isValid = ::OpenAPI::fromJsonValue(order_state, json[QString("order_state")]); + + + m_implv_isValid = ::OpenAPI::fromJsonValue(implv, json[QString("implv")]); + + + m_advanced_isValid = ::OpenAPI::fromJsonValue(advanced, json[QString("advanced")]); + + + m_post_only_isValid = ::OpenAPI::fromJsonValue(post_only, json[QString("post_only")]); + + + m_usd_isValid = ::OpenAPI::fromJsonValue(usd, json[QString("usd")]); + + + m_stop_price_isValid = ::OpenAPI::fromJsonValue(stop_price, json[QString("stop_price")]); + + + m_order_type_isValid = ::OpenAPI::fromJsonValue(order_type, json[QString("order_type")]); + + + m_last_update_timestamp_isValid = ::OpenAPI::fromJsonValue(last_update_timestamp, json[QString("last_update_timestamp")]); + + + m_original_order_type_isValid = ::OpenAPI::fromJsonValue(original_order_type, json[QString("original_order_type")]); + + + m_max_show_isValid = ::OpenAPI::fromJsonValue(max_show, json[QString("max_show")]); + + + m_profit_loss_isValid = ::OpenAPI::fromJsonValue(profit_loss, json[QString("profit_loss")]); + + + m_is_liquidation_isValid = ::OpenAPI::fromJsonValue(is_liquidation, json[QString("is_liquidation")]); + + + m_filled_amount_isValid = ::OpenAPI::fromJsonValue(filled_amount, json[QString("filled_amount")]); + + + m_label_isValid = ::OpenAPI::fromJsonValue(label, json[QString("label")]); + + + m_commission_isValid = ::OpenAPI::fromJsonValue(commission, json[QString("commission")]); + + + m_amount_isValid = ::OpenAPI::fromJsonValue(amount, json[QString("amount")]); + + + m_trigger_isValid = ::OpenAPI::fromJsonValue(trigger, json[QString("trigger")]); + + + m_instrument_name_isValid = ::OpenAPI::fromJsonValue(instrument_name, json[QString("instrument_name")]); + + + m_creation_timestamp_isValid = ::OpenAPI::fromJsonValue(creation_timestamp, json[QString("creation_timestamp")]); + + + m_average_price_isValid = ::OpenAPI::fromJsonValue(average_price, json[QString("average_price")]); + + +} + +QString +OAIOrder::asJson () const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject +OAIOrder::asJsonObject() const { + QJsonObject obj; + if(m_direction_isSet){ + obj.insert(QString("direction"), ::OpenAPI::toJsonValue(direction)); + } + if(m_reduce_only_isSet){ + obj.insert(QString("reduce_only"), ::OpenAPI::toJsonValue(reduce_only)); + } + if(m_triggered_isSet){ + obj.insert(QString("triggered"), ::OpenAPI::toJsonValue(triggered)); + } + if(m_order_id_isSet){ + obj.insert(QString("order_id"), ::OpenAPI::toJsonValue(order_id)); + } + if(m_price_isSet){ + obj.insert(QString("price"), ::OpenAPI::toJsonValue(price)); + } + if(m_time_in_force_isSet){ + obj.insert(QString("time_in_force"), ::OpenAPI::toJsonValue(time_in_force)); + } + if(m_api_isSet){ + obj.insert(QString("api"), ::OpenAPI::toJsonValue(api)); + } + if(m_order_state_isSet){ + obj.insert(QString("order_state"), ::OpenAPI::toJsonValue(order_state)); + } + if(m_implv_isSet){ + obj.insert(QString("implv"), ::OpenAPI::toJsonValue(implv)); + } + if(m_advanced_isSet){ + obj.insert(QString("advanced"), ::OpenAPI::toJsonValue(advanced)); + } + if(m_post_only_isSet){ + obj.insert(QString("post_only"), ::OpenAPI::toJsonValue(post_only)); + } + if(m_usd_isSet){ + obj.insert(QString("usd"), ::OpenAPI::toJsonValue(usd)); + } + if(m_stop_price_isSet){ + obj.insert(QString("stop_price"), ::OpenAPI::toJsonValue(stop_price)); + } + if(m_order_type_isSet){ + obj.insert(QString("order_type"), ::OpenAPI::toJsonValue(order_type)); + } + if(m_last_update_timestamp_isSet){ + obj.insert(QString("last_update_timestamp"), ::OpenAPI::toJsonValue(last_update_timestamp)); + } + if(m_original_order_type_isSet){ + obj.insert(QString("original_order_type"), ::OpenAPI::toJsonValue(original_order_type)); + } + if(m_max_show_isSet){ + obj.insert(QString("max_show"), ::OpenAPI::toJsonValue(max_show)); + } + if(m_profit_loss_isSet){ + obj.insert(QString("profit_loss"), ::OpenAPI::toJsonValue(profit_loss)); + } + if(m_is_liquidation_isSet){ + obj.insert(QString("is_liquidation"), ::OpenAPI::toJsonValue(is_liquidation)); + } + if(m_filled_amount_isSet){ + obj.insert(QString("filled_amount"), ::OpenAPI::toJsonValue(filled_amount)); + } + if(m_label_isSet){ + obj.insert(QString("label"), ::OpenAPI::toJsonValue(label)); + } + if(m_commission_isSet){ + obj.insert(QString("commission"), ::OpenAPI::toJsonValue(commission)); + } + if(m_amount_isSet){ + obj.insert(QString("amount"), ::OpenAPI::toJsonValue(amount)); + } + if(m_trigger_isSet){ + obj.insert(QString("trigger"), ::OpenAPI::toJsonValue(trigger)); + } + if(m_instrument_name_isSet){ + obj.insert(QString("instrument_name"), ::OpenAPI::toJsonValue(instrument_name)); + } + if(m_creation_timestamp_isSet){ + obj.insert(QString("creation_timestamp"), ::OpenAPI::toJsonValue(creation_timestamp)); + } + if(m_average_price_isSet){ + obj.insert(QString("average_price"), ::OpenAPI::toJsonValue(average_price)); + } + return obj; +} + + +QString +OAIOrder::getDirection() const { + return direction; +} +void +OAIOrder::setDirection(const QString &direction) { + this->direction = direction; + this->m_direction_isSet = true; +} + + +bool +OAIOrder::isReduceOnly() const { + return reduce_only; +} +void +OAIOrder::setReduceOnly(const bool &reduce_only) { + this->reduce_only = reduce_only; + this->m_reduce_only_isSet = true; +} + + +bool +OAIOrder::isTriggered() const { + return triggered; +} +void +OAIOrder::setTriggered(const bool &triggered) { + this->triggered = triggered; + this->m_triggered_isSet = true; +} + + +QString +OAIOrder::getOrderId() const { + return order_id; +} +void +OAIOrder::setOrderId(const QString &order_id) { + this->order_id = order_id; + this->m_order_id_isSet = true; +} + + +double +OAIOrder::getPrice() const { + return price; +} +void +OAIOrder::setPrice(const double &price) { + this->price = price; + this->m_price_isSet = true; +} + + +QString +OAIOrder::getTimeInForce() const { + return time_in_force; +} +void +OAIOrder::setTimeInForce(const QString &time_in_force) { + this->time_in_force = time_in_force; + this->m_time_in_force_isSet = true; +} + + +bool +OAIOrder::isApi() const { + return api; +} +void +OAIOrder::setApi(const bool &api) { + this->api = api; + this->m_api_isSet = true; +} + + +QString +OAIOrder::getOrderState() const { + return order_state; +} +void +OAIOrder::setOrderState(const QString &order_state) { + this->order_state = order_state; + this->m_order_state_isSet = true; +} + + +double +OAIOrder::getImplv() const { + return implv; +} +void +OAIOrder::setImplv(const double &implv) { + this->implv = implv; + this->m_implv_isSet = true; +} + + +QString +OAIOrder::getAdvanced() const { + return advanced; +} +void +OAIOrder::setAdvanced(const QString &advanced) { + this->advanced = advanced; + this->m_advanced_isSet = true; +} + + +bool +OAIOrder::isPostOnly() const { + return post_only; +} +void +OAIOrder::setPostOnly(const bool &post_only) { + this->post_only = post_only; + this->m_post_only_isSet = true; +} + + +double +OAIOrder::getUsd() const { + return usd; +} +void +OAIOrder::setUsd(const double &usd) { + this->usd = usd; + this->m_usd_isSet = true; +} + + +double +OAIOrder::getStopPrice() const { + return stop_price; +} +void +OAIOrder::setStopPrice(const double &stop_price) { + this->stop_price = stop_price; + this->m_stop_price_isSet = true; +} + + +QString +OAIOrder::getOrderType() const { + return order_type; +} +void +OAIOrder::setOrderType(const QString &order_type) { + this->order_type = order_type; + this->m_order_type_isSet = true; +} + + +qint32 +OAIOrder::getLastUpdateTimestamp() const { + return last_update_timestamp; +} +void +OAIOrder::setLastUpdateTimestamp(const qint32 &last_update_timestamp) { + this->last_update_timestamp = last_update_timestamp; + this->m_last_update_timestamp_isSet = true; +} + + +QString +OAIOrder::getOriginalOrderType() const { + return original_order_type; +} +void +OAIOrder::setOriginalOrderType(const QString &original_order_type) { + this->original_order_type = original_order_type; + this->m_original_order_type_isSet = true; +} + + +double +OAIOrder::getMaxShow() const { + return max_show; +} +void +OAIOrder::setMaxShow(const double &max_show) { + this->max_show = max_show; + this->m_max_show_isSet = true; +} + + +double +OAIOrder::getProfitLoss() const { + return profit_loss; +} +void +OAIOrder::setProfitLoss(const double &profit_loss) { + this->profit_loss = profit_loss; + this->m_profit_loss_isSet = true; +} + + +bool +OAIOrder::isIsLiquidation() const { + return is_liquidation; +} +void +OAIOrder::setIsLiquidation(const bool &is_liquidation) { + this->is_liquidation = is_liquidation; + this->m_is_liquidation_isSet = true; +} + + +double +OAIOrder::getFilledAmount() const { + return filled_amount; +} +void +OAIOrder::setFilledAmount(const double &filled_amount) { + this->filled_amount = filled_amount; + this->m_filled_amount_isSet = true; +} + + +QString +OAIOrder::getLabel() const { + return label; +} +void +OAIOrder::setLabel(const QString &label) { + this->label = label; + this->m_label_isSet = true; +} + + +double +OAIOrder::getCommission() const { + return commission; +} +void +OAIOrder::setCommission(const double &commission) { + this->commission = commission; + this->m_commission_isSet = true; +} + + +double +OAIOrder::getAmount() const { + return amount; +} +void +OAIOrder::setAmount(const double &amount) { + this->amount = amount; + this->m_amount_isSet = true; +} + + +QString +OAIOrder::getTrigger() const { + return trigger; +} +void +OAIOrder::setTrigger(const QString &trigger) { + this->trigger = trigger; + this->m_trigger_isSet = true; +} + + +QString +OAIOrder::getInstrumentName() const { + return instrument_name; +} +void +OAIOrder::setInstrumentName(const QString &instrument_name) { + this->instrument_name = instrument_name; + this->m_instrument_name_isSet = true; +} + + +qint32 +OAIOrder::getCreationTimestamp() const { + return creation_timestamp; +} +void +OAIOrder::setCreationTimestamp(const qint32 &creation_timestamp) { + this->creation_timestamp = creation_timestamp; + this->m_creation_timestamp_isSet = true; +} + + +double +OAIOrder::getAveragePrice() const { + return average_price; +} +void +OAIOrder::setAveragePrice(const double &average_price) { + this->average_price = average_price; + this->m_average_price_isSet = true; +} + +bool +OAIOrder::isSet() const { + bool isObjectUpdated = false; + do{ + if(m_direction_isSet){ isObjectUpdated = true; break;} + + if(m_reduce_only_isSet){ isObjectUpdated = true; break;} + + if(m_triggered_isSet){ isObjectUpdated = true; break;} + + if(m_order_id_isSet){ isObjectUpdated = true; break;} + + if(m_price_isSet){ isObjectUpdated = true; break;} + + if(m_time_in_force_isSet){ isObjectUpdated = true; break;} + + if(m_api_isSet){ isObjectUpdated = true; break;} + + if(m_order_state_isSet){ isObjectUpdated = true; break;} + + if(m_implv_isSet){ isObjectUpdated = true; break;} + + if(m_advanced_isSet){ isObjectUpdated = true; break;} + + if(m_post_only_isSet){ isObjectUpdated = true; break;} + + if(m_usd_isSet){ isObjectUpdated = true; break;} + + if(m_stop_price_isSet){ isObjectUpdated = true; break;} + + if(m_order_type_isSet){ isObjectUpdated = true; break;} + + if(m_last_update_timestamp_isSet){ isObjectUpdated = true; break;} + + if(m_original_order_type_isSet){ isObjectUpdated = true; break;} + + if(m_max_show_isSet){ isObjectUpdated = true; break;} + + if(m_profit_loss_isSet){ isObjectUpdated = true; break;} + + if(m_is_liquidation_isSet){ isObjectUpdated = true; break;} + + if(m_filled_amount_isSet){ isObjectUpdated = true; break;} + + if(m_label_isSet){ isObjectUpdated = true; break;} + + if(m_commission_isSet){ isObjectUpdated = true; break;} + + if(m_amount_isSet){ isObjectUpdated = true; break;} + + if(m_trigger_isSet){ isObjectUpdated = true; break;} + + if(m_instrument_name_isSet){ isObjectUpdated = true; break;} + + if(m_creation_timestamp_isSet){ isObjectUpdated = true; break;} + + if(m_average_price_isSet){ isObjectUpdated = true; break;} + }while(false); + return isObjectUpdated; +} + +bool +OAIOrder::isValid() const { + // only required properties are required for the object to be considered valid + return m_direction_isValid && m_order_id_isValid && m_price_isValid && m_time_in_force_isValid && m_api_isValid && m_order_state_isValid && m_post_only_isValid && m_order_type_isValid && m_last_update_timestamp_isValid && m_max_show_isValid && m_is_liquidation_isValid && m_label_isValid && m_creation_timestamp_isValid && true; +} + +} + diff --git a/cpp-qt5-client/client/OAIOrder.h b/cpp-qt5-client/client/OAIOrder.h new file mode 100644 index 0000000..2b88941 --- /dev/null +++ b/cpp-qt5-client/client/OAIOrder.h @@ -0,0 +1,271 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OAIOrder.h + * + * + */ + +#ifndef OAIOrder_H +#define OAIOrder_H + +#include + + +#include + +#include "OAIObject.h" +#include "OAIEnum.h" + +namespace OpenAPI { + +class OAIOrder: public OAIObject { +public: + OAIOrder(); + OAIOrder(QString json); + ~OAIOrder() override; + + QString asJson () const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + + QString getDirection() const; + void setDirection(const QString &direction); + + + bool isReduceOnly() const; + void setReduceOnly(const bool &reduce_only); + + + bool isTriggered() const; + void setTriggered(const bool &triggered); + + + QString getOrderId() const; + void setOrderId(const QString &order_id); + + + double getPrice() const; + void setPrice(const double &price); + + + QString getTimeInForce() const; + void setTimeInForce(const QString &time_in_force); + + + bool isApi() const; + void setApi(const bool &api); + + + QString getOrderState() const; + void setOrderState(const QString &order_state); + + + double getImplv() const; + void setImplv(const double &implv); + + + QString getAdvanced() const; + void setAdvanced(const QString &advanced); + + + bool isPostOnly() const; + void setPostOnly(const bool &post_only); + + + double getUsd() const; + void setUsd(const double &usd); + + + double getStopPrice() const; + void setStopPrice(const double &stop_price); + + + QString getOrderType() const; + void setOrderType(const QString &order_type); + + + qint32 getLastUpdateTimestamp() const; + void setLastUpdateTimestamp(const qint32 &last_update_timestamp); + + + QString getOriginalOrderType() const; + void setOriginalOrderType(const QString &original_order_type); + + + double getMaxShow() const; + void setMaxShow(const double &max_show); + + + double getProfitLoss() const; + void setProfitLoss(const double &profit_loss); + + + bool isIsLiquidation() const; + void setIsLiquidation(const bool &is_liquidation); + + + double getFilledAmount() const; + void setFilledAmount(const double &filled_amount); + + + QString getLabel() const; + void setLabel(const QString &label); + + + double getCommission() const; + void setCommission(const double &commission); + + + double getAmount() const; + void setAmount(const double &amount); + + + QString getTrigger() const; + void setTrigger(const QString &trigger); + + + QString getInstrumentName() const; + void setInstrumentName(const QString &instrument_name); + + + qint32 getCreationTimestamp() const; + void setCreationTimestamp(const qint32 &creation_timestamp); + + + double getAveragePrice() const; + void setAveragePrice(const double &average_price); + + + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void init(); + + QString direction; + bool m_direction_isSet; + bool m_direction_isValid; + + bool reduce_only; + bool m_reduce_only_isSet; + bool m_reduce_only_isValid; + + bool triggered; + bool m_triggered_isSet; + bool m_triggered_isValid; + + QString order_id; + bool m_order_id_isSet; + bool m_order_id_isValid; + + double price; + bool m_price_isSet; + bool m_price_isValid; + + QString time_in_force; + bool m_time_in_force_isSet; + bool m_time_in_force_isValid; + + bool api; + bool m_api_isSet; + bool m_api_isValid; + + QString order_state; + bool m_order_state_isSet; + bool m_order_state_isValid; + + double implv; + bool m_implv_isSet; + bool m_implv_isValid; + + QString advanced; + bool m_advanced_isSet; + bool m_advanced_isValid; + + bool post_only; + bool m_post_only_isSet; + bool m_post_only_isValid; + + double usd; + bool m_usd_isSet; + bool m_usd_isValid; + + double stop_price; + bool m_stop_price_isSet; + bool m_stop_price_isValid; + + QString order_type; + bool m_order_type_isSet; + bool m_order_type_isValid; + + qint32 last_update_timestamp; + bool m_last_update_timestamp_isSet; + bool m_last_update_timestamp_isValid; + + QString original_order_type; + bool m_original_order_type_isSet; + bool m_original_order_type_isValid; + + double max_show; + bool m_max_show_isSet; + bool m_max_show_isValid; + + double profit_loss; + bool m_profit_loss_isSet; + bool m_profit_loss_isValid; + + bool is_liquidation; + bool m_is_liquidation_isSet; + bool m_is_liquidation_isValid; + + double filled_amount; + bool m_filled_amount_isSet; + bool m_filled_amount_isValid; + + QString label; + bool m_label_isSet; + bool m_label_isValid; + + double commission; + bool m_commission_isSet; + bool m_commission_isValid; + + double amount; + bool m_amount_isSet; + bool m_amount_isValid; + + QString trigger; + bool m_trigger_isSet; + bool m_trigger_isValid; + + QString instrument_name; + bool m_instrument_name_isSet; + bool m_instrument_name_isValid; + + qint32 creation_timestamp; + bool m_creation_timestamp_isSet; + bool m_creation_timestamp_isValid; + + double average_price; + bool m_average_price_isSet; + bool m_average_price_isValid; + + }; + +} + +#endif // OAIOrder_H diff --git a/cpp-qt5-client/client/OAIOrder_id_initial_margin_pair.cpp b/cpp-qt5-client/client/OAIOrder_id_initial_margin_pair.cpp new file mode 100644 index 0000000..11463a1 --- /dev/null +++ b/cpp-qt5-client/client/OAIOrder_id_initial_margin_pair.cpp @@ -0,0 +1,127 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include "OAIOrder_id_initial_margin_pair.h" + +#include "OAIHelpers.h" + +#include +#include +#include +#include + +namespace OpenAPI { + +OAIOrder_id_initial_margin_pair::OAIOrder_id_initial_margin_pair(QString json) { + this->init(); + this->fromJson(json); +} + +OAIOrder_id_initial_margin_pair::OAIOrder_id_initial_margin_pair() { + this->init(); +} + +OAIOrder_id_initial_margin_pair::~OAIOrder_id_initial_margin_pair() { + +} + +void +OAIOrder_id_initial_margin_pair::init() { + + m_order_id_isSet = false; + m_order_id_isValid = false; + + m_initial_margin_isSet = false; + m_initial_margin_isValid = false; + } + +void +OAIOrder_id_initial_margin_pair::fromJson(QString jsonString) { + QByteArray array (jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void +OAIOrder_id_initial_margin_pair::fromJsonObject(QJsonObject json) { + + m_order_id_isValid = ::OpenAPI::fromJsonValue(order_id, json[QString("order_id")]); + + + m_initial_margin_isValid = ::OpenAPI::fromJsonValue(initial_margin, json[QString("initial_margin")]); + + +} + +QString +OAIOrder_id_initial_margin_pair::asJson () const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject +OAIOrder_id_initial_margin_pair::asJsonObject() const { + QJsonObject obj; + if(m_order_id_isSet){ + obj.insert(QString("order_id"), ::OpenAPI::toJsonValue(order_id)); + } + if(m_initial_margin_isSet){ + obj.insert(QString("initial_margin"), ::OpenAPI::toJsonValue(initial_margin)); + } + return obj; +} + + +QString +OAIOrder_id_initial_margin_pair::getOrderId() const { + return order_id; +} +void +OAIOrder_id_initial_margin_pair::setOrderId(const QString &order_id) { + this->order_id = order_id; + this->m_order_id_isSet = true; +} + + +double +OAIOrder_id_initial_margin_pair::getInitialMargin() const { + return initial_margin; +} +void +OAIOrder_id_initial_margin_pair::setInitialMargin(const double &initial_margin) { + this->initial_margin = initial_margin; + this->m_initial_margin_isSet = true; +} + +bool +OAIOrder_id_initial_margin_pair::isSet() const { + bool isObjectUpdated = false; + do{ + if(m_order_id_isSet){ isObjectUpdated = true; break;} + + if(m_initial_margin_isSet){ isObjectUpdated = true; break;} + }while(false); + return isObjectUpdated; +} + +bool +OAIOrder_id_initial_margin_pair::isValid() const { + // only required properties are required for the object to be considered valid + return m_order_id_isValid && m_initial_margin_isValid && true; +} + +} + diff --git a/cpp-qt5-client/client/OAIOrder_id_initial_margin_pair.h b/cpp-qt5-client/client/OAIOrder_id_initial_margin_pair.h new file mode 100644 index 0000000..52db5a1 --- /dev/null +++ b/cpp-qt5-client/client/OAIOrder_id_initial_margin_pair.h @@ -0,0 +1,71 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OAIOrder_id_initial_margin_pair.h + * + * + */ + +#ifndef OAIOrder_id_initial_margin_pair_H +#define OAIOrder_id_initial_margin_pair_H + +#include + + +#include + +#include "OAIObject.h" +#include "OAIEnum.h" + +namespace OpenAPI { + +class OAIOrder_id_initial_margin_pair: public OAIObject { +public: + OAIOrder_id_initial_margin_pair(); + OAIOrder_id_initial_margin_pair(QString json); + ~OAIOrder_id_initial_margin_pair() override; + + QString asJson () const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + + QString getOrderId() const; + void setOrderId(const QString &order_id); + + + double getInitialMargin() const; + void setInitialMargin(const double &initial_margin); + + + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void init(); + + QString order_id; + bool m_order_id_isSet; + bool m_order_id_isValid; + + double initial_margin; + bool m_initial_margin_isSet; + bool m_initial_margin_isValid; + + }; + +} + +#endif // OAIOrder_id_initial_margin_pair_H diff --git a/cpp-qt5-client/client/OAIPortfolio.cpp b/cpp-qt5-client/client/OAIPortfolio.cpp new file mode 100644 index 0000000..1744cd3 --- /dev/null +++ b/cpp-qt5-client/client/OAIPortfolio.cpp @@ -0,0 +1,127 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include "OAIPortfolio.h" + +#include "OAIHelpers.h" + +#include +#include +#include +#include + +namespace OpenAPI { + +OAIPortfolio::OAIPortfolio(QString json) { + this->init(); + this->fromJson(json); +} + +OAIPortfolio::OAIPortfolio() { + this->init(); +} + +OAIPortfolio::~OAIPortfolio() { + +} + +void +OAIPortfolio::init() { + + m_eth_isSet = false; + m_eth_isValid = false; + + m_btc_isSet = false; + m_btc_isValid = false; + } + +void +OAIPortfolio::fromJson(QString jsonString) { + QByteArray array (jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void +OAIPortfolio::fromJsonObject(QJsonObject json) { + + m_eth_isValid = ::OpenAPI::fromJsonValue(eth, json[QString("eth")]); + + + m_btc_isValid = ::OpenAPI::fromJsonValue(btc, json[QString("btc")]); + + +} + +QString +OAIPortfolio::asJson () const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject +OAIPortfolio::asJsonObject() const { + QJsonObject obj; + if(eth.isSet()){ + obj.insert(QString("eth"), ::OpenAPI::toJsonValue(eth)); + } + if(btc.isSet()){ + obj.insert(QString("btc"), ::OpenAPI::toJsonValue(btc)); + } + return obj; +} + + +OAIPortfolio_eth +OAIPortfolio::getEth() const { + return eth; +} +void +OAIPortfolio::setEth(const OAIPortfolio_eth ð) { + this->eth = eth; + this->m_eth_isSet = true; +} + + +OAIPortfolio_eth +OAIPortfolio::getBtc() const { + return btc; +} +void +OAIPortfolio::setBtc(const OAIPortfolio_eth &btc) { + this->btc = btc; + this->m_btc_isSet = true; +} + +bool +OAIPortfolio::isSet() const { + bool isObjectUpdated = false; + do{ + if(eth.isSet()){ isObjectUpdated = true; break;} + + if(btc.isSet()){ isObjectUpdated = true; break;} + }while(false); + return isObjectUpdated; +} + +bool +OAIPortfolio::isValid() const { + // only required properties are required for the object to be considered valid + return m_eth_isValid && m_btc_isValid && true; +} + +} + diff --git a/cpp-qt5-client/client/OAIPortfolio.h b/cpp-qt5-client/client/OAIPortfolio.h new file mode 100644 index 0000000..39ad012 --- /dev/null +++ b/cpp-qt5-client/client/OAIPortfolio.h @@ -0,0 +1,71 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OAIPortfolio.h + * + * + */ + +#ifndef OAIPortfolio_H +#define OAIPortfolio_H + +#include + + +#include "OAIPortfolio_eth.h" + +#include "OAIObject.h" +#include "OAIEnum.h" + +namespace OpenAPI { + +class OAIPortfolio: public OAIObject { +public: + OAIPortfolio(); + OAIPortfolio(QString json); + ~OAIPortfolio() override; + + QString asJson () const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + + OAIPortfolio_eth getEth() const; + void setEth(const OAIPortfolio_eth ð); + + + OAIPortfolio_eth getBtc() const; + void setBtc(const OAIPortfolio_eth &btc); + + + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void init(); + + OAIPortfolio_eth eth; + bool m_eth_isSet; + bool m_eth_isValid; + + OAIPortfolio_eth btc; + bool m_btc_isSet; + bool m_btc_isValid; + + }; + +} + +#endif // OAIPortfolio_H diff --git a/cpp-qt5-client/client/OAIPortfolio_eth.cpp b/cpp-qt5-client/client/OAIPortfolio_eth.cpp new file mode 100644 index 0000000..48f5096 --- /dev/null +++ b/cpp-qt5-client/client/OAIPortfolio_eth.cpp @@ -0,0 +1,259 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include "OAIPortfolio_eth.h" + +#include "OAIHelpers.h" + +#include +#include +#include +#include + +namespace OpenAPI { + +OAIPortfolio_eth::OAIPortfolio_eth(QString json) { + this->init(); + this->fromJson(json); +} + +OAIPortfolio_eth::OAIPortfolio_eth() { + this->init(); +} + +OAIPortfolio_eth::~OAIPortfolio_eth() { + +} + +void +OAIPortfolio_eth::init() { + + m_maintenance_margin_isSet = false; + m_maintenance_margin_isValid = false; + + m_available_withdrawal_funds_isSet = false; + m_available_withdrawal_funds_isValid = false; + + m_initial_margin_isSet = false; + m_initial_margin_isValid = false; + + m_available_funds_isSet = false; + m_available_funds_isValid = false; + + m_currency_isSet = false; + m_currency_isValid = false; + + m_margin_balance_isSet = false; + m_margin_balance_isValid = false; + + m_equity_isSet = false; + m_equity_isValid = false; + + m_balance_isSet = false; + m_balance_isValid = false; + } + +void +OAIPortfolio_eth::fromJson(QString jsonString) { + QByteArray array (jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void +OAIPortfolio_eth::fromJsonObject(QJsonObject json) { + + m_maintenance_margin_isValid = ::OpenAPI::fromJsonValue(maintenance_margin, json[QString("maintenance_margin")]); + + + m_available_withdrawal_funds_isValid = ::OpenAPI::fromJsonValue(available_withdrawal_funds, json[QString("available_withdrawal_funds")]); + + + m_initial_margin_isValid = ::OpenAPI::fromJsonValue(initial_margin, json[QString("initial_margin")]); + + + m_available_funds_isValid = ::OpenAPI::fromJsonValue(available_funds, json[QString("available_funds")]); + + + m_currency_isValid = ::OpenAPI::fromJsonValue(currency, json[QString("currency")]); + + + m_margin_balance_isValid = ::OpenAPI::fromJsonValue(margin_balance, json[QString("margin_balance")]); + + + m_equity_isValid = ::OpenAPI::fromJsonValue(equity, json[QString("equity")]); + + + m_balance_isValid = ::OpenAPI::fromJsonValue(balance, json[QString("balance")]); + + +} + +QString +OAIPortfolio_eth::asJson () const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject +OAIPortfolio_eth::asJsonObject() const { + QJsonObject obj; + if(m_maintenance_margin_isSet){ + obj.insert(QString("maintenance_margin"), ::OpenAPI::toJsonValue(maintenance_margin)); + } + if(m_available_withdrawal_funds_isSet){ + obj.insert(QString("available_withdrawal_funds"), ::OpenAPI::toJsonValue(available_withdrawal_funds)); + } + if(m_initial_margin_isSet){ + obj.insert(QString("initial_margin"), ::OpenAPI::toJsonValue(initial_margin)); + } + if(m_available_funds_isSet){ + obj.insert(QString("available_funds"), ::OpenAPI::toJsonValue(available_funds)); + } + if(m_currency_isSet){ + obj.insert(QString("currency"), ::OpenAPI::toJsonValue(currency)); + } + if(m_margin_balance_isSet){ + obj.insert(QString("margin_balance"), ::OpenAPI::toJsonValue(margin_balance)); + } + if(m_equity_isSet){ + obj.insert(QString("equity"), ::OpenAPI::toJsonValue(equity)); + } + if(m_balance_isSet){ + obj.insert(QString("balance"), ::OpenAPI::toJsonValue(balance)); + } + return obj; +} + + +double +OAIPortfolio_eth::getMaintenanceMargin() const { + return maintenance_margin; +} +void +OAIPortfolio_eth::setMaintenanceMargin(const double &maintenance_margin) { + this->maintenance_margin = maintenance_margin; + this->m_maintenance_margin_isSet = true; +} + + +double +OAIPortfolio_eth::getAvailableWithdrawalFunds() const { + return available_withdrawal_funds; +} +void +OAIPortfolio_eth::setAvailableWithdrawalFunds(const double &available_withdrawal_funds) { + this->available_withdrawal_funds = available_withdrawal_funds; + this->m_available_withdrawal_funds_isSet = true; +} + + +double +OAIPortfolio_eth::getInitialMargin() const { + return initial_margin; +} +void +OAIPortfolio_eth::setInitialMargin(const double &initial_margin) { + this->initial_margin = initial_margin; + this->m_initial_margin_isSet = true; +} + + +double +OAIPortfolio_eth::getAvailableFunds() const { + return available_funds; +} +void +OAIPortfolio_eth::setAvailableFunds(const double &available_funds) { + this->available_funds = available_funds; + this->m_available_funds_isSet = true; +} + + +QString +OAIPortfolio_eth::getCurrency() const { + return currency; +} +void +OAIPortfolio_eth::setCurrency(const QString ¤cy) { + this->currency = currency; + this->m_currency_isSet = true; +} + + +double +OAIPortfolio_eth::getMarginBalance() const { + return margin_balance; +} +void +OAIPortfolio_eth::setMarginBalance(const double &margin_balance) { + this->margin_balance = margin_balance; + this->m_margin_balance_isSet = true; +} + + +double +OAIPortfolio_eth::getEquity() const { + return equity; +} +void +OAIPortfolio_eth::setEquity(const double &equity) { + this->equity = equity; + this->m_equity_isSet = true; +} + + +double +OAIPortfolio_eth::getBalance() const { + return balance; +} +void +OAIPortfolio_eth::setBalance(const double &balance) { + this->balance = balance; + this->m_balance_isSet = true; +} + +bool +OAIPortfolio_eth::isSet() const { + bool isObjectUpdated = false; + do{ + if(m_maintenance_margin_isSet){ isObjectUpdated = true; break;} + + if(m_available_withdrawal_funds_isSet){ isObjectUpdated = true; break;} + + if(m_initial_margin_isSet){ isObjectUpdated = true; break;} + + if(m_available_funds_isSet){ isObjectUpdated = true; break;} + + if(m_currency_isSet){ isObjectUpdated = true; break;} + + if(m_margin_balance_isSet){ isObjectUpdated = true; break;} + + if(m_equity_isSet){ isObjectUpdated = true; break;} + + if(m_balance_isSet){ isObjectUpdated = true; break;} + }while(false); + return isObjectUpdated; +} + +bool +OAIPortfolio_eth::isValid() const { + // only required properties are required for the object to be considered valid + return m_maintenance_margin_isValid && m_available_withdrawal_funds_isValid && m_initial_margin_isValid && m_available_funds_isValid && m_currency_isValid && m_margin_balance_isValid && m_equity_isValid && m_balance_isValid && true; +} + +} + diff --git a/cpp-qt5-client/client/OAIPortfolio_eth.h b/cpp-qt5-client/client/OAIPortfolio_eth.h new file mode 100644 index 0000000..10008ae --- /dev/null +++ b/cpp-qt5-client/client/OAIPortfolio_eth.h @@ -0,0 +1,119 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OAIPortfolio_eth.h + * + * + */ + +#ifndef OAIPortfolio_eth_H +#define OAIPortfolio_eth_H + +#include + + +#include + +#include "OAIObject.h" +#include "OAIEnum.h" + +namespace OpenAPI { + +class OAIPortfolio_eth: public OAIObject { +public: + OAIPortfolio_eth(); + OAIPortfolio_eth(QString json); + ~OAIPortfolio_eth() override; + + QString asJson () const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + + double getMaintenanceMargin() const; + void setMaintenanceMargin(const double &maintenance_margin); + + + double getAvailableWithdrawalFunds() const; + void setAvailableWithdrawalFunds(const double &available_withdrawal_funds); + + + double getInitialMargin() const; + void setInitialMargin(const double &initial_margin); + + + double getAvailableFunds() const; + void setAvailableFunds(const double &available_funds); + + + QString getCurrency() const; + void setCurrency(const QString ¤cy); + + + double getMarginBalance() const; + void setMarginBalance(const double &margin_balance); + + + double getEquity() const; + void setEquity(const double &equity); + + + double getBalance() const; + void setBalance(const double &balance); + + + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void init(); + + double maintenance_margin; + bool m_maintenance_margin_isSet; + bool m_maintenance_margin_isValid; + + double available_withdrawal_funds; + bool m_available_withdrawal_funds_isSet; + bool m_available_withdrawal_funds_isValid; + + double initial_margin; + bool m_initial_margin_isSet; + bool m_initial_margin_isValid; + + double available_funds; + bool m_available_funds_isSet; + bool m_available_funds_isValid; + + QString currency; + bool m_currency_isSet; + bool m_currency_isValid; + + double margin_balance; + bool m_margin_balance_isSet; + bool m_margin_balance_isValid; + + double equity; + bool m_equity_isSet; + bool m_equity_isValid; + + double balance; + bool m_balance_isSet; + bool m_balance_isValid; + + }; + +} + +#endif // OAIPortfolio_eth_H diff --git a/cpp-qt5-client/client/OAIPosition.cpp b/cpp-qt5-client/client/OAIPosition.cpp new file mode 100644 index 0000000..dfccfc6 --- /dev/null +++ b/cpp-qt5-client/client/OAIPosition.cpp @@ -0,0 +1,501 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include "OAIPosition.h" + +#include "OAIHelpers.h" + +#include +#include +#include +#include + +namespace OpenAPI { + +OAIPosition::OAIPosition(QString json) { + this->init(); + this->fromJson(json); +} + +OAIPosition::OAIPosition() { + this->init(); +} + +OAIPosition::~OAIPosition() { + +} + +void +OAIPosition::init() { + + m_direction_isSet = false; + m_direction_isValid = false; + + m_average_price_usd_isSet = false; + m_average_price_usd_isValid = false; + + m_estimated_liquidation_price_isSet = false; + m_estimated_liquidation_price_isValid = false; + + m_floating_profit_loss_isSet = false; + m_floating_profit_loss_isValid = false; + + m_floating_profit_loss_usd_isSet = false; + m_floating_profit_loss_usd_isValid = false; + + m_open_orders_margin_isSet = false; + m_open_orders_margin_isValid = false; + + m_total_profit_loss_isSet = false; + m_total_profit_loss_isValid = false; + + m_realized_profit_loss_isSet = false; + m_realized_profit_loss_isValid = false; + + m_delta_isSet = false; + m_delta_isValid = false; + + m_initial_margin_isSet = false; + m_initial_margin_isValid = false; + + m_size_isSet = false; + m_size_isValid = false; + + m_maintenance_margin_isSet = false; + m_maintenance_margin_isValid = false; + + m_kind_isSet = false; + m_kind_isValid = false; + + m_mark_price_isSet = false; + m_mark_price_isValid = false; + + m_average_price_isSet = false; + m_average_price_isValid = false; + + m_settlement_price_isSet = false; + m_settlement_price_isValid = false; + + m_index_price_isSet = false; + m_index_price_isValid = false; + + m_instrument_name_isSet = false; + m_instrument_name_isValid = false; + + m_size_currency_isSet = false; + m_size_currency_isValid = false; + } + +void +OAIPosition::fromJson(QString jsonString) { + QByteArray array (jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void +OAIPosition::fromJsonObject(QJsonObject json) { + + m_direction_isValid = ::OpenAPI::fromJsonValue(direction, json[QString("direction")]); + + + m_average_price_usd_isValid = ::OpenAPI::fromJsonValue(average_price_usd, json[QString("average_price_usd")]); + + + m_estimated_liquidation_price_isValid = ::OpenAPI::fromJsonValue(estimated_liquidation_price, json[QString("estimated_liquidation_price")]); + + + m_floating_profit_loss_isValid = ::OpenAPI::fromJsonValue(floating_profit_loss, json[QString("floating_profit_loss")]); + + + m_floating_profit_loss_usd_isValid = ::OpenAPI::fromJsonValue(floating_profit_loss_usd, json[QString("floating_profit_loss_usd")]); + + + m_open_orders_margin_isValid = ::OpenAPI::fromJsonValue(open_orders_margin, json[QString("open_orders_margin")]); + + + m_total_profit_loss_isValid = ::OpenAPI::fromJsonValue(total_profit_loss, json[QString("total_profit_loss")]); + + + m_realized_profit_loss_isValid = ::OpenAPI::fromJsonValue(realized_profit_loss, json[QString("realized_profit_loss")]); + + + m_delta_isValid = ::OpenAPI::fromJsonValue(delta, json[QString("delta")]); + + + m_initial_margin_isValid = ::OpenAPI::fromJsonValue(initial_margin, json[QString("initial_margin")]); + + + m_size_isValid = ::OpenAPI::fromJsonValue(size, json[QString("size")]); + + + m_maintenance_margin_isValid = ::OpenAPI::fromJsonValue(maintenance_margin, json[QString("maintenance_margin")]); + + + m_kind_isValid = ::OpenAPI::fromJsonValue(kind, json[QString("kind")]); + + + m_mark_price_isValid = ::OpenAPI::fromJsonValue(mark_price, json[QString("mark_price")]); + + + m_average_price_isValid = ::OpenAPI::fromJsonValue(average_price, json[QString("average_price")]); + + + m_settlement_price_isValid = ::OpenAPI::fromJsonValue(settlement_price, json[QString("settlement_price")]); + + + m_index_price_isValid = ::OpenAPI::fromJsonValue(index_price, json[QString("index_price")]); + + + m_instrument_name_isValid = ::OpenAPI::fromJsonValue(instrument_name, json[QString("instrument_name")]); + + + m_size_currency_isValid = ::OpenAPI::fromJsonValue(size_currency, json[QString("size_currency")]); + + +} + +QString +OAIPosition::asJson () const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject +OAIPosition::asJsonObject() const { + QJsonObject obj; + if(m_direction_isSet){ + obj.insert(QString("direction"), ::OpenAPI::toJsonValue(direction)); + } + if(m_average_price_usd_isSet){ + obj.insert(QString("average_price_usd"), ::OpenAPI::toJsonValue(average_price_usd)); + } + if(m_estimated_liquidation_price_isSet){ + obj.insert(QString("estimated_liquidation_price"), ::OpenAPI::toJsonValue(estimated_liquidation_price)); + } + if(m_floating_profit_loss_isSet){ + obj.insert(QString("floating_profit_loss"), ::OpenAPI::toJsonValue(floating_profit_loss)); + } + if(m_floating_profit_loss_usd_isSet){ + obj.insert(QString("floating_profit_loss_usd"), ::OpenAPI::toJsonValue(floating_profit_loss_usd)); + } + if(m_open_orders_margin_isSet){ + obj.insert(QString("open_orders_margin"), ::OpenAPI::toJsonValue(open_orders_margin)); + } + if(m_total_profit_loss_isSet){ + obj.insert(QString("total_profit_loss"), ::OpenAPI::toJsonValue(total_profit_loss)); + } + if(m_realized_profit_loss_isSet){ + obj.insert(QString("realized_profit_loss"), ::OpenAPI::toJsonValue(realized_profit_loss)); + } + if(m_delta_isSet){ + obj.insert(QString("delta"), ::OpenAPI::toJsonValue(delta)); + } + if(m_initial_margin_isSet){ + obj.insert(QString("initial_margin"), ::OpenAPI::toJsonValue(initial_margin)); + } + if(m_size_isSet){ + obj.insert(QString("size"), ::OpenAPI::toJsonValue(size)); + } + if(m_maintenance_margin_isSet){ + obj.insert(QString("maintenance_margin"), ::OpenAPI::toJsonValue(maintenance_margin)); + } + if(m_kind_isSet){ + obj.insert(QString("kind"), ::OpenAPI::toJsonValue(kind)); + } + if(m_mark_price_isSet){ + obj.insert(QString("mark_price"), ::OpenAPI::toJsonValue(mark_price)); + } + if(m_average_price_isSet){ + obj.insert(QString("average_price"), ::OpenAPI::toJsonValue(average_price)); + } + if(m_settlement_price_isSet){ + obj.insert(QString("settlement_price"), ::OpenAPI::toJsonValue(settlement_price)); + } + if(m_index_price_isSet){ + obj.insert(QString("index_price"), ::OpenAPI::toJsonValue(index_price)); + } + if(m_instrument_name_isSet){ + obj.insert(QString("instrument_name"), ::OpenAPI::toJsonValue(instrument_name)); + } + if(m_size_currency_isSet){ + obj.insert(QString("size_currency"), ::OpenAPI::toJsonValue(size_currency)); + } + return obj; +} + + +QString +OAIPosition::getDirection() const { + return direction; +} +void +OAIPosition::setDirection(const QString &direction) { + this->direction = direction; + this->m_direction_isSet = true; +} + + +double +OAIPosition::getAveragePriceUsd() const { + return average_price_usd; +} +void +OAIPosition::setAveragePriceUsd(const double &average_price_usd) { + this->average_price_usd = average_price_usd; + this->m_average_price_usd_isSet = true; +} + + +double +OAIPosition::getEstimatedLiquidationPrice() const { + return estimated_liquidation_price; +} +void +OAIPosition::setEstimatedLiquidationPrice(const double &estimated_liquidation_price) { + this->estimated_liquidation_price = estimated_liquidation_price; + this->m_estimated_liquidation_price_isSet = true; +} + + +double +OAIPosition::getFloatingProfitLoss() const { + return floating_profit_loss; +} +void +OAIPosition::setFloatingProfitLoss(const double &floating_profit_loss) { + this->floating_profit_loss = floating_profit_loss; + this->m_floating_profit_loss_isSet = true; +} + + +double +OAIPosition::getFloatingProfitLossUsd() const { + return floating_profit_loss_usd; +} +void +OAIPosition::setFloatingProfitLossUsd(const double &floating_profit_loss_usd) { + this->floating_profit_loss_usd = floating_profit_loss_usd; + this->m_floating_profit_loss_usd_isSet = true; +} + + +double +OAIPosition::getOpenOrdersMargin() const { + return open_orders_margin; +} +void +OAIPosition::setOpenOrdersMargin(const double &open_orders_margin) { + this->open_orders_margin = open_orders_margin; + this->m_open_orders_margin_isSet = true; +} + + +double +OAIPosition::getTotalProfitLoss() const { + return total_profit_loss; +} +void +OAIPosition::setTotalProfitLoss(const double &total_profit_loss) { + this->total_profit_loss = total_profit_loss; + this->m_total_profit_loss_isSet = true; +} + + +double +OAIPosition::getRealizedProfitLoss() const { + return realized_profit_loss; +} +void +OAIPosition::setRealizedProfitLoss(const double &realized_profit_loss) { + this->realized_profit_loss = realized_profit_loss; + this->m_realized_profit_loss_isSet = true; +} + + +double +OAIPosition::getDelta() const { + return delta; +} +void +OAIPosition::setDelta(const double &delta) { + this->delta = delta; + this->m_delta_isSet = true; +} + + +double +OAIPosition::getInitialMargin() const { + return initial_margin; +} +void +OAIPosition::setInitialMargin(const double &initial_margin) { + this->initial_margin = initial_margin; + this->m_initial_margin_isSet = true; +} + + +double +OAIPosition::getSize() const { + return size; +} +void +OAIPosition::setSize(const double &size) { + this->size = size; + this->m_size_isSet = true; +} + + +double +OAIPosition::getMaintenanceMargin() const { + return maintenance_margin; +} +void +OAIPosition::setMaintenanceMargin(const double &maintenance_margin) { + this->maintenance_margin = maintenance_margin; + this->m_maintenance_margin_isSet = true; +} + + +QString +OAIPosition::getKind() const { + return kind; +} +void +OAIPosition::setKind(const QString &kind) { + this->kind = kind; + this->m_kind_isSet = true; +} + + +double +OAIPosition::getMarkPrice() const { + return mark_price; +} +void +OAIPosition::setMarkPrice(const double &mark_price) { + this->mark_price = mark_price; + this->m_mark_price_isSet = true; +} + + +double +OAIPosition::getAveragePrice() const { + return average_price; +} +void +OAIPosition::setAveragePrice(const double &average_price) { + this->average_price = average_price; + this->m_average_price_isSet = true; +} + + +double +OAIPosition::getSettlementPrice() const { + return settlement_price; +} +void +OAIPosition::setSettlementPrice(const double &settlement_price) { + this->settlement_price = settlement_price; + this->m_settlement_price_isSet = true; +} + + +double +OAIPosition::getIndexPrice() const { + return index_price; +} +void +OAIPosition::setIndexPrice(const double &index_price) { + this->index_price = index_price; + this->m_index_price_isSet = true; +} + + +QString +OAIPosition::getInstrumentName() const { + return instrument_name; +} +void +OAIPosition::setInstrumentName(const QString &instrument_name) { + this->instrument_name = instrument_name; + this->m_instrument_name_isSet = true; +} + + +double +OAIPosition::getSizeCurrency() const { + return size_currency; +} +void +OAIPosition::setSizeCurrency(const double &size_currency) { + this->size_currency = size_currency; + this->m_size_currency_isSet = true; +} + +bool +OAIPosition::isSet() const { + bool isObjectUpdated = false; + do{ + if(m_direction_isSet){ isObjectUpdated = true; break;} + + if(m_average_price_usd_isSet){ isObjectUpdated = true; break;} + + if(m_estimated_liquidation_price_isSet){ isObjectUpdated = true; break;} + + if(m_floating_profit_loss_isSet){ isObjectUpdated = true; break;} + + if(m_floating_profit_loss_usd_isSet){ isObjectUpdated = true; break;} + + if(m_open_orders_margin_isSet){ isObjectUpdated = true; break;} + + if(m_total_profit_loss_isSet){ isObjectUpdated = true; break;} + + if(m_realized_profit_loss_isSet){ isObjectUpdated = true; break;} + + if(m_delta_isSet){ isObjectUpdated = true; break;} + + if(m_initial_margin_isSet){ isObjectUpdated = true; break;} + + if(m_size_isSet){ isObjectUpdated = true; break;} + + if(m_maintenance_margin_isSet){ isObjectUpdated = true; break;} + + if(m_kind_isSet){ isObjectUpdated = true; break;} + + if(m_mark_price_isSet){ isObjectUpdated = true; break;} + + if(m_average_price_isSet){ isObjectUpdated = true; break;} + + if(m_settlement_price_isSet){ isObjectUpdated = true; break;} + + if(m_index_price_isSet){ isObjectUpdated = true; break;} + + if(m_instrument_name_isSet){ isObjectUpdated = true; break;} + + if(m_size_currency_isSet){ isObjectUpdated = true; break;} + }while(false); + return isObjectUpdated; +} + +bool +OAIPosition::isValid() const { + // only required properties are required for the object to be considered valid + return m_direction_isValid && m_floating_profit_loss_isValid && m_open_orders_margin_isValid && m_total_profit_loss_isValid && m_delta_isValid && m_initial_margin_isValid && m_size_isValid && m_maintenance_margin_isValid && m_kind_isValid && m_mark_price_isValid && m_average_price_isValid && m_settlement_price_isValid && m_index_price_isValid && m_instrument_name_isValid && true; +} + +} + diff --git a/cpp-qt5-client/client/OAIPosition.h b/cpp-qt5-client/client/OAIPosition.h new file mode 100644 index 0000000..edce951 --- /dev/null +++ b/cpp-qt5-client/client/OAIPosition.h @@ -0,0 +1,207 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OAIPosition.h + * + * + */ + +#ifndef OAIPosition_H +#define OAIPosition_H + +#include + + +#include + +#include "OAIObject.h" +#include "OAIEnum.h" + +namespace OpenAPI { + +class OAIPosition: public OAIObject { +public: + OAIPosition(); + OAIPosition(QString json); + ~OAIPosition() override; + + QString asJson () const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + + QString getDirection() const; + void setDirection(const QString &direction); + + + double getAveragePriceUsd() const; + void setAveragePriceUsd(const double &average_price_usd); + + + double getEstimatedLiquidationPrice() const; + void setEstimatedLiquidationPrice(const double &estimated_liquidation_price); + + + double getFloatingProfitLoss() const; + void setFloatingProfitLoss(const double &floating_profit_loss); + + + double getFloatingProfitLossUsd() const; + void setFloatingProfitLossUsd(const double &floating_profit_loss_usd); + + + double getOpenOrdersMargin() const; + void setOpenOrdersMargin(const double &open_orders_margin); + + + double getTotalProfitLoss() const; + void setTotalProfitLoss(const double &total_profit_loss); + + + double getRealizedProfitLoss() const; + void setRealizedProfitLoss(const double &realized_profit_loss); + + + double getDelta() const; + void setDelta(const double &delta); + + + double getInitialMargin() const; + void setInitialMargin(const double &initial_margin); + + + double getSize() const; + void setSize(const double &size); + + + double getMaintenanceMargin() const; + void setMaintenanceMargin(const double &maintenance_margin); + + + QString getKind() const; + void setKind(const QString &kind); + + + double getMarkPrice() const; + void setMarkPrice(const double &mark_price); + + + double getAveragePrice() const; + void setAveragePrice(const double &average_price); + + + double getSettlementPrice() const; + void setSettlementPrice(const double &settlement_price); + + + double getIndexPrice() const; + void setIndexPrice(const double &index_price); + + + QString getInstrumentName() const; + void setInstrumentName(const QString &instrument_name); + + + double getSizeCurrency() const; + void setSizeCurrency(const double &size_currency); + + + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void init(); + + QString direction; + bool m_direction_isSet; + bool m_direction_isValid; + + double average_price_usd; + bool m_average_price_usd_isSet; + bool m_average_price_usd_isValid; + + double estimated_liquidation_price; + bool m_estimated_liquidation_price_isSet; + bool m_estimated_liquidation_price_isValid; + + double floating_profit_loss; + bool m_floating_profit_loss_isSet; + bool m_floating_profit_loss_isValid; + + double floating_profit_loss_usd; + bool m_floating_profit_loss_usd_isSet; + bool m_floating_profit_loss_usd_isValid; + + double open_orders_margin; + bool m_open_orders_margin_isSet; + bool m_open_orders_margin_isValid; + + double total_profit_loss; + bool m_total_profit_loss_isSet; + bool m_total_profit_loss_isValid; + + double realized_profit_loss; + bool m_realized_profit_loss_isSet; + bool m_realized_profit_loss_isValid; + + double delta; + bool m_delta_isSet; + bool m_delta_isValid; + + double initial_margin; + bool m_initial_margin_isSet; + bool m_initial_margin_isValid; + + double size; + bool m_size_isSet; + bool m_size_isValid; + + double maintenance_margin; + bool m_maintenance_margin_isSet; + bool m_maintenance_margin_isValid; + + QString kind; + bool m_kind_isSet; + bool m_kind_isValid; + + double mark_price; + bool m_mark_price_isSet; + bool m_mark_price_isValid; + + double average_price; + bool m_average_price_isSet; + bool m_average_price_isValid; + + double settlement_price; + bool m_settlement_price_isSet; + bool m_settlement_price_isValid; + + double index_price; + bool m_index_price_isSet; + bool m_index_price_isValid; + + QString instrument_name; + bool m_instrument_name_isSet; + bool m_instrument_name_isValid; + + double size_currency; + bool m_size_currency_isSet; + bool m_size_currency_isValid; + + }; + +} + +#endif // OAIPosition_H diff --git a/cpp-qt5-client/client/OAIPrivateApi.cpp b/cpp-qt5-client/client/OAIPrivateApi.cpp new file mode 100644 index 0000000..3e4c64f --- /dev/null +++ b/cpp-qt5-client/client/OAIPrivateApi.cpp @@ -0,0 +1,3669 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "OAIPrivateApi.h" +#include "OAIHelpers.h" + +#include +#include + +namespace OpenAPI { + +OAIPrivateApi::OAIPrivateApi() : basePath("/api/v2"), + host("www.deribit.com") { + +} + +OAIPrivateApi::~OAIPrivateApi() { + +} + +OAIPrivateApi::OAIPrivateApi(const QString& host, const QString& basePath) { + this->host = host; + this->basePath = basePath; +} + +void OAIPrivateApi::setBasePath(const QString& basePath){ + this->basePath = basePath; +} + +void OAIPrivateApi::setHost(const QString& host){ + this->host = host; +} + +void OAIPrivateApi::addHeaders(const QString& key, const QString& value){ + defaultHeaders.insert(key, value); +} + + +void +OAIPrivateApi::privateAddToAddressBookGet(const QString& currency, const QString& type, const QString& address, const QString& name, const QString& tfa) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/add_to_address_book"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("address")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(address))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("tfa")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(tfa))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateAddToAddressBookGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateAddToAddressBookGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateAddToAddressBookGetSignal(output); + emit privateAddToAddressBookGetSignalFull(worker, output); + } else { + emit privateAddToAddressBookGetSignalE(output, error_type, error_str); + emit privateAddToAddressBookGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateBuyGet(const QString& instrument_name, const double& amount, const QString& type, const QString& label, const double& price, const QString& time_in_force, const double& max_show, const bool& post_only, const bool& reduce_only, const double& stop_price, const QString& trigger, const QString& advanced) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/buy"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("amount")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(amount))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("label")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(label))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("price")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(price))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("time_in_force")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(time_in_force))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("max_show")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(max_show))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("post_only")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(post_only))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("reduce_only")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(reduce_only))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("stop_price")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(stop_price))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("trigger")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(trigger))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("advanced")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(advanced))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateBuyGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateBuyGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateBuyGetSignal(output); + emit privateBuyGetSignalFull(worker, output); + } else { + emit privateBuyGetSignalE(output, error_type, error_str); + emit privateBuyGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateCancelAllByCurrencyGet(const QString& currency, const QString& kind, const QString& type) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/cancel_all_by_currency"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("kind")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(kind))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateCancelAllByCurrencyGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateCancelAllByCurrencyGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateCancelAllByCurrencyGetSignal(output); + emit privateCancelAllByCurrencyGetSignalFull(worker, output); + } else { + emit privateCancelAllByCurrencyGetSignalE(output, error_type, error_str); + emit privateCancelAllByCurrencyGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateCancelAllByInstrumentGet(const QString& instrument_name, const QString& type) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/cancel_all_by_instrument"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateCancelAllByInstrumentGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateCancelAllByInstrumentGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateCancelAllByInstrumentGetSignal(output); + emit privateCancelAllByInstrumentGetSignalFull(worker, output); + } else { + emit privateCancelAllByInstrumentGetSignalE(output, error_type, error_str); + emit privateCancelAllByInstrumentGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateCancelAllGet() { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/cancel_all"); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateCancelAllGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateCancelAllGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateCancelAllGetSignal(output); + emit privateCancelAllGetSignalFull(worker, output); + } else { + emit privateCancelAllGetSignalE(output, error_type, error_str); + emit privateCancelAllGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateCancelGet(const QString& order_id) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/cancel"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("order_id")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(order_id))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateCancelGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateCancelGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateCancelGetSignal(output); + emit privateCancelGetSignalFull(worker, output); + } else { + emit privateCancelGetSignalE(output, error_type, error_str); + emit privateCancelGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateCancelTransferByIdGet(const QString& currency, const qint32& id, const QString& tfa) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/cancel_transfer_by_id"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("id")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(id))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("tfa")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(tfa))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateCancelTransferByIdGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateCancelTransferByIdGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateCancelTransferByIdGetSignal(output); + emit privateCancelTransferByIdGetSignalFull(worker, output); + } else { + emit privateCancelTransferByIdGetSignalE(output, error_type, error_str); + emit privateCancelTransferByIdGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateCancelWithdrawalGet(const QString& currency, const double& id) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/cancel_withdrawal"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("id")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(id))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateCancelWithdrawalGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateCancelWithdrawalGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateCancelWithdrawalGetSignal(output); + emit privateCancelWithdrawalGetSignalFull(worker, output); + } else { + emit privateCancelWithdrawalGetSignalE(output, error_type, error_str); + emit privateCancelWithdrawalGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateChangeSubaccountNameGet(const qint32& sid, const QString& name) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/change_subaccount_name"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sid")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sid))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(name))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateChangeSubaccountNameGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateChangeSubaccountNameGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateChangeSubaccountNameGetSignal(output); + emit privateChangeSubaccountNameGetSignalFull(worker, output); + } else { + emit privateChangeSubaccountNameGetSignalE(output, error_type, error_str); + emit privateChangeSubaccountNameGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateClosePositionGet(const QString& instrument_name, const QString& type, const double& price) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/close_position"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("price")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(price))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateClosePositionGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateClosePositionGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateClosePositionGetSignal(output); + emit privateClosePositionGetSignalFull(worker, output); + } else { + emit privateClosePositionGetSignalE(output, error_type, error_str); + emit privateClosePositionGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateCreateDepositAddressGet(const QString& currency) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/create_deposit_address"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateCreateDepositAddressGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateCreateDepositAddressGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateCreateDepositAddressGetSignal(output); + emit privateCreateDepositAddressGetSignalFull(worker, output); + } else { + emit privateCreateDepositAddressGetSignalE(output, error_type, error_str); + emit privateCreateDepositAddressGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateCreateSubaccountGet() { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/create_subaccount"); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateCreateSubaccountGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateCreateSubaccountGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateCreateSubaccountGetSignal(output); + emit privateCreateSubaccountGetSignalFull(worker, output); + } else { + emit privateCreateSubaccountGetSignalE(output, error_type, error_str); + emit privateCreateSubaccountGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateDisableTfaForSubaccountGet(const qint32& sid) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/disable_tfa_for_subaccount"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sid")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sid))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateDisableTfaForSubaccountGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateDisableTfaForSubaccountGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateDisableTfaForSubaccountGetSignal(output); + emit privateDisableTfaForSubaccountGetSignalFull(worker, output); + } else { + emit privateDisableTfaForSubaccountGetSignalE(output, error_type, error_str); + emit privateDisableTfaForSubaccountGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateDisableTfaWithRecoveryCodeGet(const QString& password, const QString& code) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/disable_tfa_with_recovery_code"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("password")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(password))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("code")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(code))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateDisableTfaWithRecoveryCodeGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateDisableTfaWithRecoveryCodeGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateDisableTfaWithRecoveryCodeGetSignal(output); + emit privateDisableTfaWithRecoveryCodeGetSignalFull(worker, output); + } else { + emit privateDisableTfaWithRecoveryCodeGetSignalE(output, error_type, error_str); + emit privateDisableTfaWithRecoveryCodeGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateEditGet(const QString& order_id, const double& amount, const double& price, const bool& post_only, const QString& advanced, const double& stop_price) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/edit"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("order_id")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(order_id))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("amount")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(amount))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("price")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(price))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("post_only")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(post_only))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("advanced")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(advanced))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("stop_price")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(stop_price))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateEditGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateEditGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateEditGetSignal(output); + emit privateEditGetSignalFull(worker, output); + } else { + emit privateEditGetSignalE(output, error_type, error_str); + emit privateEditGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetAccountSummaryGet(const QString& currency, const bool& extended) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_account_summary"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("extended")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(extended))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetAccountSummaryGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetAccountSummaryGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetAccountSummaryGetSignal(output); + emit privateGetAccountSummaryGetSignalFull(worker, output); + } else { + emit privateGetAccountSummaryGetSignalE(output, error_type, error_str); + emit privateGetAccountSummaryGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetAddressBookGet(const QString& currency, const QString& type) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_address_book"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetAddressBookGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetAddressBookGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetAddressBookGetSignal(output); + emit privateGetAddressBookGetSignalFull(worker, output); + } else { + emit privateGetAddressBookGetSignalE(output, error_type, error_str); + emit privateGetAddressBookGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetCurrentDepositAddressGet(const QString& currency) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_current_deposit_address"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetCurrentDepositAddressGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetCurrentDepositAddressGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetCurrentDepositAddressGetSignal(output); + emit privateGetCurrentDepositAddressGetSignalFull(worker, output); + } else { + emit privateGetCurrentDepositAddressGetSignalE(output, error_type, error_str); + emit privateGetCurrentDepositAddressGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetDepositsGet(const QString& currency, const qint32& count, const qint32& offset) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_deposits"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("offset")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(offset))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetDepositsGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetDepositsGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetDepositsGetSignal(output); + emit privateGetDepositsGetSignalFull(worker, output); + } else { + emit privateGetDepositsGetSignalE(output, error_type, error_str); + emit privateGetDepositsGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetEmailLanguageGet() { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_email_language"); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetEmailLanguageGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetEmailLanguageGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetEmailLanguageGetSignal(output); + emit privateGetEmailLanguageGetSignalFull(worker, output); + } else { + emit privateGetEmailLanguageGetSignalE(output, error_type, error_str); + emit privateGetEmailLanguageGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetMarginsGet(const QString& instrument_name, const double& amount, const double& price) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_margins"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("amount")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(amount))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("price")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(price))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetMarginsGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetMarginsGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetMarginsGetSignal(output); + emit privateGetMarginsGetSignalFull(worker, output); + } else { + emit privateGetMarginsGetSignalE(output, error_type, error_str); + emit privateGetMarginsGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetNewAnnouncementsGet() { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_new_announcements"); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetNewAnnouncementsGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetNewAnnouncementsGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetNewAnnouncementsGetSignal(output); + emit privateGetNewAnnouncementsGetSignalFull(worker, output); + } else { + emit privateGetNewAnnouncementsGetSignalE(output, error_type, error_str); + emit privateGetNewAnnouncementsGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetOpenOrdersByCurrencyGet(const QString& currency, const QString& kind, const QString& type) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_open_orders_by_currency"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("kind")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(kind))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetOpenOrdersByCurrencyGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetOpenOrdersByCurrencyGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetOpenOrdersByCurrencyGetSignal(output); + emit privateGetOpenOrdersByCurrencyGetSignalFull(worker, output); + } else { + emit privateGetOpenOrdersByCurrencyGetSignalE(output, error_type, error_str); + emit privateGetOpenOrdersByCurrencyGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetOpenOrdersByInstrumentGet(const QString& instrument_name, const QString& type) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_open_orders_by_instrument"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetOpenOrdersByInstrumentGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetOpenOrdersByInstrumentGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetOpenOrdersByInstrumentGetSignal(output); + emit privateGetOpenOrdersByInstrumentGetSignalFull(worker, output); + } else { + emit privateGetOpenOrdersByInstrumentGetSignalE(output, error_type, error_str); + emit privateGetOpenOrdersByInstrumentGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetOrderHistoryByCurrencyGet(const QString& currency, const QString& kind, const qint32& count, const qint32& offset, const bool& include_old, const bool& include_unfilled) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_order_history_by_currency"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("kind")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(kind))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("offset")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(offset))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("include_old")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(include_old))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("include_unfilled")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(include_unfilled))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetOrderHistoryByCurrencyGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetOrderHistoryByCurrencyGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetOrderHistoryByCurrencyGetSignal(output); + emit privateGetOrderHistoryByCurrencyGetSignalFull(worker, output); + } else { + emit privateGetOrderHistoryByCurrencyGetSignalE(output, error_type, error_str); + emit privateGetOrderHistoryByCurrencyGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetOrderHistoryByInstrumentGet(const QString& instrument_name, const qint32& count, const qint32& offset, const bool& include_old, const bool& include_unfilled) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_order_history_by_instrument"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("offset")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(offset))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("include_old")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(include_old))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("include_unfilled")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(include_unfilled))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetOrderHistoryByInstrumentGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetOrderHistoryByInstrumentGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetOrderHistoryByInstrumentGetSignal(output); + emit privateGetOrderHistoryByInstrumentGetSignalFull(worker, output); + } else { + emit privateGetOrderHistoryByInstrumentGetSignalE(output, error_type, error_str); + emit privateGetOrderHistoryByInstrumentGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetOrderMarginByIdsGet(const QList& ids) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_order_margin_by_ids"); + + if (ids.size() > 0) { + if (QString("multi").indexOf("multi") == 0) { + foreach(QString t, ids) { + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append("ids=").append(::OpenAPI::toStringValue(t)); + } + } + else if (QString("multi").indexOf("ssv") == 0) { + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append("ids="); + qint32 count = 0; + foreach(QString t, ids) { + if (count > 0) { + fullPath.append(" "); + } + fullPath.append(::OpenAPI::toStringValue(t)); + } + } + else if (QString("multi").indexOf("tsv") == 0) { + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append("ids="); + qint32 count = 0; + foreach(QString t, ids) { + if (count > 0) { + fullPath.append("\t"); + } + fullPath.append(::OpenAPI::toStringValue(t)); + } + } + } + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetOrderMarginByIdsGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetOrderMarginByIdsGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetOrderMarginByIdsGetSignal(output); + emit privateGetOrderMarginByIdsGetSignalFull(worker, output); + } else { + emit privateGetOrderMarginByIdsGetSignalE(output, error_type, error_str); + emit privateGetOrderMarginByIdsGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetOrderStateGet(const QString& order_id) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_order_state"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("order_id")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(order_id))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetOrderStateGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetOrderStateGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetOrderStateGetSignal(output); + emit privateGetOrderStateGetSignalFull(worker, output); + } else { + emit privateGetOrderStateGetSignalE(output, error_type, error_str); + emit privateGetOrderStateGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetPositionGet(const QString& instrument_name) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_position"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetPositionGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetPositionGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetPositionGetSignal(output); + emit privateGetPositionGetSignalFull(worker, output); + } else { + emit privateGetPositionGetSignalE(output, error_type, error_str); + emit privateGetPositionGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetPositionsGet(const QString& currency, const QString& kind) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_positions"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("kind")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(kind))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetPositionsGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetPositionsGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetPositionsGetSignal(output); + emit privateGetPositionsGetSignalFull(worker, output); + } else { + emit privateGetPositionsGetSignalE(output, error_type, error_str); + emit privateGetPositionsGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetSettlementHistoryByCurrencyGet(const QString& currency, const QString& type, const qint32& count) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_settlement_history_by_currency"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetSettlementHistoryByCurrencyGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetSettlementHistoryByCurrencyGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetSettlementHistoryByCurrencyGetSignal(output); + emit privateGetSettlementHistoryByCurrencyGetSignalFull(worker, output); + } else { + emit privateGetSettlementHistoryByCurrencyGetSignalE(output, error_type, error_str); + emit privateGetSettlementHistoryByCurrencyGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetSettlementHistoryByInstrumentGet(const QString& instrument_name, const QString& type, const qint32& count) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_settlement_history_by_instrument"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetSettlementHistoryByInstrumentGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetSettlementHistoryByInstrumentGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetSettlementHistoryByInstrumentGetSignal(output); + emit privateGetSettlementHistoryByInstrumentGetSignalFull(worker, output); + } else { + emit privateGetSettlementHistoryByInstrumentGetSignalE(output, error_type, error_str); + emit privateGetSettlementHistoryByInstrumentGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetSubaccountsGet(const bool& with_portfolio) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_subaccounts"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("with_portfolio")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(with_portfolio))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetSubaccountsGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetSubaccountsGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetSubaccountsGetSignal(output); + emit privateGetSubaccountsGetSignalFull(worker, output); + } else { + emit privateGetSubaccountsGetSignalE(output, error_type, error_str); + emit privateGetSubaccountsGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetTransfersGet(const QString& currency, const qint32& count, const qint32& offset) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_transfers"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("offset")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(offset))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetTransfersGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetTransfersGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetTransfersGetSignal(output); + emit privateGetTransfersGetSignalFull(worker, output); + } else { + emit privateGetTransfersGetSignalE(output, error_type, error_str); + emit privateGetTransfersGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetUserTradesByCurrencyAndTimeGet(const QString& currency, const qint32& start_timestamp, const qint32& end_timestamp, const QString& kind, const qint32& count, const bool& include_old, const QString& sorting) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_user_trades_by_currency_and_time"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("kind")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(kind))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("start_timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(start_timestamp))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("end_timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(end_timestamp))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("include_old")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(include_old))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sorting")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sorting))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetUserTradesByCurrencyAndTimeGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetUserTradesByCurrencyAndTimeGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetUserTradesByCurrencyAndTimeGetSignal(output); + emit privateGetUserTradesByCurrencyAndTimeGetSignalFull(worker, output); + } else { + emit privateGetUserTradesByCurrencyAndTimeGetSignalE(output, error_type, error_str); + emit privateGetUserTradesByCurrencyAndTimeGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetUserTradesByCurrencyGet(const QString& currency, const QString& kind, const QString& start_id, const QString& end_id, const qint32& count, const bool& include_old, const QString& sorting) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_user_trades_by_currency"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("kind")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(kind))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("start_id")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(start_id))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("end_id")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(end_id))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("include_old")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(include_old))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sorting")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sorting))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetUserTradesByCurrencyGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetUserTradesByCurrencyGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetUserTradesByCurrencyGetSignal(output); + emit privateGetUserTradesByCurrencyGetSignalFull(worker, output); + } else { + emit privateGetUserTradesByCurrencyGetSignalE(output, error_type, error_str); + emit privateGetUserTradesByCurrencyGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetUserTradesByInstrumentAndTimeGet(const QString& instrument_name, const qint32& start_timestamp, const qint32& end_timestamp, const qint32& count, const bool& include_old, const QString& sorting) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_user_trades_by_instrument_and_time"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("start_timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(start_timestamp))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("end_timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(end_timestamp))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("include_old")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(include_old))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sorting")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sorting))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetUserTradesByInstrumentAndTimeGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetUserTradesByInstrumentAndTimeGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetUserTradesByInstrumentAndTimeGetSignal(output); + emit privateGetUserTradesByInstrumentAndTimeGetSignalFull(worker, output); + } else { + emit privateGetUserTradesByInstrumentAndTimeGetSignalE(output, error_type, error_str); + emit privateGetUserTradesByInstrumentAndTimeGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetUserTradesByInstrumentGet(const QString& instrument_name, const qint32& start_seq, const qint32& end_seq, const qint32& count, const bool& include_old, const QString& sorting) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_user_trades_by_instrument"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("start_seq")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(start_seq))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("end_seq")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(end_seq))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("include_old")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(include_old))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sorting")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sorting))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetUserTradesByInstrumentGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetUserTradesByInstrumentGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetUserTradesByInstrumentGetSignal(output); + emit privateGetUserTradesByInstrumentGetSignalFull(worker, output); + } else { + emit privateGetUserTradesByInstrumentGetSignalE(output, error_type, error_str); + emit privateGetUserTradesByInstrumentGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetUserTradesByOrderGet(const QString& order_id, const QString& sorting) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_user_trades_by_order"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("order_id")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(order_id))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sorting")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sorting))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetUserTradesByOrderGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetUserTradesByOrderGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetUserTradesByOrderGetSignal(output); + emit privateGetUserTradesByOrderGetSignalFull(worker, output); + } else { + emit privateGetUserTradesByOrderGetSignalE(output, error_type, error_str); + emit privateGetUserTradesByOrderGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateGetWithdrawalsGet(const QString& currency, const qint32& count, const qint32& offset) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_withdrawals"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("offset")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(offset))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateGetWithdrawalsGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateGetWithdrawalsGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetWithdrawalsGetSignal(output); + emit privateGetWithdrawalsGetSignalFull(worker, output); + } else { + emit privateGetWithdrawalsGetSignalE(output, error_type, error_str); + emit privateGetWithdrawalsGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateRemoveFromAddressBookGet(const QString& currency, const QString& type, const QString& address, const QString& tfa) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/remove_from_address_book"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("address")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(address))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("tfa")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(tfa))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateRemoveFromAddressBookGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateRemoveFromAddressBookGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateRemoveFromAddressBookGetSignal(output); + emit privateRemoveFromAddressBookGetSignalFull(worker, output); + } else { + emit privateRemoveFromAddressBookGetSignalE(output, error_type, error_str); + emit privateRemoveFromAddressBookGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateSellGet(const QString& instrument_name, const double& amount, const QString& type, const QString& label, const double& price, const QString& time_in_force, const double& max_show, const bool& post_only, const bool& reduce_only, const double& stop_price, const QString& trigger, const QString& advanced) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/sell"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("amount")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(amount))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("label")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(label))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("price")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(price))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("time_in_force")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(time_in_force))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("max_show")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(max_show))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("post_only")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(post_only))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("reduce_only")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(reduce_only))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("stop_price")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(stop_price))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("trigger")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(trigger))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("advanced")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(advanced))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateSellGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateSellGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateSellGetSignal(output); + emit privateSellGetSignalFull(worker, output); + } else { + emit privateSellGetSignalE(output, error_type, error_str); + emit privateSellGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateSetAnnouncementAsReadGet(const double& announcement_id) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/set_announcement_as_read"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("announcement_id")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(announcement_id))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateSetAnnouncementAsReadGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateSetAnnouncementAsReadGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateSetAnnouncementAsReadGetSignal(output); + emit privateSetAnnouncementAsReadGetSignalFull(worker, output); + } else { + emit privateSetAnnouncementAsReadGetSignalE(output, error_type, error_str); + emit privateSetAnnouncementAsReadGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateSetEmailForSubaccountGet(const qint32& sid, const QString& email) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/set_email_for_subaccount"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sid")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sid))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("email")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(email))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateSetEmailForSubaccountGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateSetEmailForSubaccountGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateSetEmailForSubaccountGetSignal(output); + emit privateSetEmailForSubaccountGetSignalFull(worker, output); + } else { + emit privateSetEmailForSubaccountGetSignalE(output, error_type, error_str); + emit privateSetEmailForSubaccountGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateSetEmailLanguageGet(const QString& language) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/set_email_language"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("language")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(language))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateSetEmailLanguageGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateSetEmailLanguageGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateSetEmailLanguageGetSignal(output); + emit privateSetEmailLanguageGetSignalFull(worker, output); + } else { + emit privateSetEmailLanguageGetSignalE(output, error_type, error_str); + emit privateSetEmailLanguageGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateSetPasswordForSubaccountGet(const qint32& sid, const QString& password) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/set_password_for_subaccount"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sid")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sid))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("password")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(password))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateSetPasswordForSubaccountGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateSetPasswordForSubaccountGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateSetPasswordForSubaccountGetSignal(output); + emit privateSetPasswordForSubaccountGetSignalFull(worker, output); + } else { + emit privateSetPasswordForSubaccountGetSignalE(output, error_type, error_str); + emit privateSetPasswordForSubaccountGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateSubmitTransferToSubaccountGet(const QString& currency, const double& amount, const qint32& destination) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/submit_transfer_to_subaccount"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("amount")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(amount))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("destination")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(destination))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateSubmitTransferToSubaccountGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateSubmitTransferToSubaccountGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateSubmitTransferToSubaccountGetSignal(output); + emit privateSubmitTransferToSubaccountGetSignalFull(worker, output); + } else { + emit privateSubmitTransferToSubaccountGetSignalE(output, error_type, error_str); + emit privateSubmitTransferToSubaccountGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateSubmitTransferToUserGet(const QString& currency, const double& amount, const QString& destination, const QString& tfa) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/submit_transfer_to_user"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("amount")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(amount))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("destination")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(destination))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("tfa")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(tfa))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateSubmitTransferToUserGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateSubmitTransferToUserGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateSubmitTransferToUserGetSignal(output); + emit privateSubmitTransferToUserGetSignalFull(worker, output); + } else { + emit privateSubmitTransferToUserGetSignalE(output, error_type, error_str); + emit privateSubmitTransferToUserGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateToggleDepositAddressCreationGet(const QString& currency, const bool& state) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/toggle_deposit_address_creation"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("state")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(state))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateToggleDepositAddressCreationGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateToggleDepositAddressCreationGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateToggleDepositAddressCreationGetSignal(output); + emit privateToggleDepositAddressCreationGetSignalFull(worker, output); + } else { + emit privateToggleDepositAddressCreationGetSignalE(output, error_type, error_str); + emit privateToggleDepositAddressCreationGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateToggleNotificationsFromSubaccountGet(const qint32& sid, const bool& state) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/toggle_notifications_from_subaccount"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sid")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sid))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("state")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(state))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateToggleNotificationsFromSubaccountGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateToggleNotificationsFromSubaccountGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateToggleNotificationsFromSubaccountGetSignal(output); + emit privateToggleNotificationsFromSubaccountGetSignalFull(worker, output); + } else { + emit privateToggleNotificationsFromSubaccountGetSignalE(output, error_type, error_str); + emit privateToggleNotificationsFromSubaccountGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateToggleSubaccountLoginGet(const qint32& sid, const QString& state) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/toggle_subaccount_login"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sid")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sid))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("state")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(state))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateToggleSubaccountLoginGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateToggleSubaccountLoginGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateToggleSubaccountLoginGetSignal(output); + emit privateToggleSubaccountLoginGetSignalFull(worker, output); + } else { + emit privateToggleSubaccountLoginGetSignalE(output, error_type, error_str); + emit privateToggleSubaccountLoginGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPrivateApi::privateWithdrawGet(const QString& currency, const QString& address, const double& amount, const QString& priority, const QString& tfa) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/withdraw"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("address")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(address))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("amount")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(amount))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("priority")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(priority))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("tfa")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(tfa))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPrivateApi::privateWithdrawGetCallback); + + worker->execute(&input); +} + +void +OAIPrivateApi::privateWithdrawGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateWithdrawGetSignal(output); + emit privateWithdrawGetSignalFull(worker, output); + } else { + emit privateWithdrawGetSignalE(output, error_type, error_str); + emit privateWithdrawGetSignalEFull(worker, error_type, error_str); + } +} + + +} diff --git a/cpp-qt5-client/client/OAIPrivateApi.h b/cpp-qt5-client/client/OAIPrivateApi.h new file mode 100644 index 0000000..a1d4b7b --- /dev/null +++ b/cpp-qt5-client/client/OAIPrivateApi.h @@ -0,0 +1,363 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#ifndef OAI_OAIPrivateApi_H +#define OAI_OAIPrivateApi_H + +#include "OAIHttpRequest.h" + +#include "OAIObject.h" +#include + +#include + +namespace OpenAPI { + +class OAIPrivateApi: public QObject { + Q_OBJECT + +public: + OAIPrivateApi(); + OAIPrivateApi(const QString& host, const QString& basePath); + ~OAIPrivateApi(); + + void setBasePath(const QString& basePath); + void setHost(const QString& host); + void addHeaders(const QString& key, const QString& value); + + void privateAddToAddressBookGet(const QString& currency, const QString& type, const QString& address, const QString& name, const QString& tfa); + void privateBuyGet(const QString& instrument_name, const double& amount, const QString& type, const QString& label, const double& price, const QString& time_in_force, const double& max_show, const bool& post_only, const bool& reduce_only, const double& stop_price, const QString& trigger, const QString& advanced); + void privateCancelAllByCurrencyGet(const QString& currency, const QString& kind, const QString& type); + void privateCancelAllByInstrumentGet(const QString& instrument_name, const QString& type); + void privateCancelAllGet(); + void privateCancelGet(const QString& order_id); + void privateCancelTransferByIdGet(const QString& currency, const qint32& id, const QString& tfa); + void privateCancelWithdrawalGet(const QString& currency, const double& id); + void privateChangeSubaccountNameGet(const qint32& sid, const QString& name); + void privateClosePositionGet(const QString& instrument_name, const QString& type, const double& price); + void privateCreateDepositAddressGet(const QString& currency); + void privateCreateSubaccountGet(); + void privateDisableTfaForSubaccountGet(const qint32& sid); + void privateDisableTfaWithRecoveryCodeGet(const QString& password, const QString& code); + void privateEditGet(const QString& order_id, const double& amount, const double& price, const bool& post_only, const QString& advanced, const double& stop_price); + void privateGetAccountSummaryGet(const QString& currency, const bool& extended); + void privateGetAddressBookGet(const QString& currency, const QString& type); + void privateGetCurrentDepositAddressGet(const QString& currency); + void privateGetDepositsGet(const QString& currency, const qint32& count, const qint32& offset); + void privateGetEmailLanguageGet(); + void privateGetMarginsGet(const QString& instrument_name, const double& amount, const double& price); + void privateGetNewAnnouncementsGet(); + void privateGetOpenOrdersByCurrencyGet(const QString& currency, const QString& kind, const QString& type); + void privateGetOpenOrdersByInstrumentGet(const QString& instrument_name, const QString& type); + void privateGetOrderHistoryByCurrencyGet(const QString& currency, const QString& kind, const qint32& count, const qint32& offset, const bool& include_old, const bool& include_unfilled); + void privateGetOrderHistoryByInstrumentGet(const QString& instrument_name, const qint32& count, const qint32& offset, const bool& include_old, const bool& include_unfilled); + void privateGetOrderMarginByIdsGet(const QList& ids); + void privateGetOrderStateGet(const QString& order_id); + void privateGetPositionGet(const QString& instrument_name); + void privateGetPositionsGet(const QString& currency, const QString& kind); + void privateGetSettlementHistoryByCurrencyGet(const QString& currency, const QString& type, const qint32& count); + void privateGetSettlementHistoryByInstrumentGet(const QString& instrument_name, const QString& type, const qint32& count); + void privateGetSubaccountsGet(const bool& with_portfolio); + void privateGetTransfersGet(const QString& currency, const qint32& count, const qint32& offset); + void privateGetUserTradesByCurrencyAndTimeGet(const QString& currency, const qint32& start_timestamp, const qint32& end_timestamp, const QString& kind, const qint32& count, const bool& include_old, const QString& sorting); + void privateGetUserTradesByCurrencyGet(const QString& currency, const QString& kind, const QString& start_id, const QString& end_id, const qint32& count, const bool& include_old, const QString& sorting); + void privateGetUserTradesByInstrumentAndTimeGet(const QString& instrument_name, const qint32& start_timestamp, const qint32& end_timestamp, const qint32& count, const bool& include_old, const QString& sorting); + void privateGetUserTradesByInstrumentGet(const QString& instrument_name, const qint32& start_seq, const qint32& end_seq, const qint32& count, const bool& include_old, const QString& sorting); + void privateGetUserTradesByOrderGet(const QString& order_id, const QString& sorting); + void privateGetWithdrawalsGet(const QString& currency, const qint32& count, const qint32& offset); + void privateRemoveFromAddressBookGet(const QString& currency, const QString& type, const QString& address, const QString& tfa); + void privateSellGet(const QString& instrument_name, const double& amount, const QString& type, const QString& label, const double& price, const QString& time_in_force, const double& max_show, const bool& post_only, const bool& reduce_only, const double& stop_price, const QString& trigger, const QString& advanced); + void privateSetAnnouncementAsReadGet(const double& announcement_id); + void privateSetEmailForSubaccountGet(const qint32& sid, const QString& email); + void privateSetEmailLanguageGet(const QString& language); + void privateSetPasswordForSubaccountGet(const qint32& sid, const QString& password); + void privateSubmitTransferToSubaccountGet(const QString& currency, const double& amount, const qint32& destination); + void privateSubmitTransferToUserGet(const QString& currency, const double& amount, const QString& destination, const QString& tfa); + void privateToggleDepositAddressCreationGet(const QString& currency, const bool& state); + void privateToggleNotificationsFromSubaccountGet(const qint32& sid, const bool& state); + void privateToggleSubaccountLoginGet(const qint32& sid, const QString& state); + void privateWithdrawGet(const QString& currency, const QString& address, const double& amount, const QString& priority, const QString& tfa); + +private: + QString basePath; + QString host; + QMap defaultHeaders; + void privateAddToAddressBookGetCallback (OAIHttpRequestWorker * worker); + void privateBuyGetCallback (OAIHttpRequestWorker * worker); + void privateCancelAllByCurrencyGetCallback (OAIHttpRequestWorker * worker); + void privateCancelAllByInstrumentGetCallback (OAIHttpRequestWorker * worker); + void privateCancelAllGetCallback (OAIHttpRequestWorker * worker); + void privateCancelGetCallback (OAIHttpRequestWorker * worker); + void privateCancelTransferByIdGetCallback (OAIHttpRequestWorker * worker); + void privateCancelWithdrawalGetCallback (OAIHttpRequestWorker * worker); + void privateChangeSubaccountNameGetCallback (OAIHttpRequestWorker * worker); + void privateClosePositionGetCallback (OAIHttpRequestWorker * worker); + void privateCreateDepositAddressGetCallback (OAIHttpRequestWorker * worker); + void privateCreateSubaccountGetCallback (OAIHttpRequestWorker * worker); + void privateDisableTfaForSubaccountGetCallback (OAIHttpRequestWorker * worker); + void privateDisableTfaWithRecoveryCodeGetCallback (OAIHttpRequestWorker * worker); + void privateEditGetCallback (OAIHttpRequestWorker * worker); + void privateGetAccountSummaryGetCallback (OAIHttpRequestWorker * worker); + void privateGetAddressBookGetCallback (OAIHttpRequestWorker * worker); + void privateGetCurrentDepositAddressGetCallback (OAIHttpRequestWorker * worker); + void privateGetDepositsGetCallback (OAIHttpRequestWorker * worker); + void privateGetEmailLanguageGetCallback (OAIHttpRequestWorker * worker); + void privateGetMarginsGetCallback (OAIHttpRequestWorker * worker); + void privateGetNewAnnouncementsGetCallback (OAIHttpRequestWorker * worker); + void privateGetOpenOrdersByCurrencyGetCallback (OAIHttpRequestWorker * worker); + void privateGetOpenOrdersByInstrumentGetCallback (OAIHttpRequestWorker * worker); + void privateGetOrderHistoryByCurrencyGetCallback (OAIHttpRequestWorker * worker); + void privateGetOrderHistoryByInstrumentGetCallback (OAIHttpRequestWorker * worker); + void privateGetOrderMarginByIdsGetCallback (OAIHttpRequestWorker * worker); + void privateGetOrderStateGetCallback (OAIHttpRequestWorker * worker); + void privateGetPositionGetCallback (OAIHttpRequestWorker * worker); + void privateGetPositionsGetCallback (OAIHttpRequestWorker * worker); + void privateGetSettlementHistoryByCurrencyGetCallback (OAIHttpRequestWorker * worker); + void privateGetSettlementHistoryByInstrumentGetCallback (OAIHttpRequestWorker * worker); + void privateGetSubaccountsGetCallback (OAIHttpRequestWorker * worker); + void privateGetTransfersGetCallback (OAIHttpRequestWorker * worker); + void privateGetUserTradesByCurrencyAndTimeGetCallback (OAIHttpRequestWorker * worker); + void privateGetUserTradesByCurrencyGetCallback (OAIHttpRequestWorker * worker); + void privateGetUserTradesByInstrumentAndTimeGetCallback (OAIHttpRequestWorker * worker); + void privateGetUserTradesByInstrumentGetCallback (OAIHttpRequestWorker * worker); + void privateGetUserTradesByOrderGetCallback (OAIHttpRequestWorker * worker); + void privateGetWithdrawalsGetCallback (OAIHttpRequestWorker * worker); + void privateRemoveFromAddressBookGetCallback (OAIHttpRequestWorker * worker); + void privateSellGetCallback (OAIHttpRequestWorker * worker); + void privateSetAnnouncementAsReadGetCallback (OAIHttpRequestWorker * worker); + void privateSetEmailForSubaccountGetCallback (OAIHttpRequestWorker * worker); + void privateSetEmailLanguageGetCallback (OAIHttpRequestWorker * worker); + void privateSetPasswordForSubaccountGetCallback (OAIHttpRequestWorker * worker); + void privateSubmitTransferToSubaccountGetCallback (OAIHttpRequestWorker * worker); + void privateSubmitTransferToUserGetCallback (OAIHttpRequestWorker * worker); + void privateToggleDepositAddressCreationGetCallback (OAIHttpRequestWorker * worker); + void privateToggleNotificationsFromSubaccountGetCallback (OAIHttpRequestWorker * worker); + void privateToggleSubaccountLoginGetCallback (OAIHttpRequestWorker * worker); + void privateWithdrawGetCallback (OAIHttpRequestWorker * worker); + +signals: + void privateAddToAddressBookGetSignal(OAIObject summary); + void privateBuyGetSignal(OAIObject summary); + void privateCancelAllByCurrencyGetSignal(OAIObject summary); + void privateCancelAllByInstrumentGetSignal(OAIObject summary); + void privateCancelAllGetSignal(OAIObject summary); + void privateCancelGetSignal(OAIObject summary); + void privateCancelTransferByIdGetSignal(OAIObject summary); + void privateCancelWithdrawalGetSignal(OAIObject summary); + void privateChangeSubaccountNameGetSignal(OAIObject summary); + void privateClosePositionGetSignal(OAIObject summary); + void privateCreateDepositAddressGetSignal(OAIObject summary); + void privateCreateSubaccountGetSignal(OAIObject summary); + void privateDisableTfaForSubaccountGetSignal(OAIObject summary); + void privateDisableTfaWithRecoveryCodeGetSignal(OAIObject summary); + void privateEditGetSignal(OAIObject summary); + void privateGetAccountSummaryGetSignal(OAIObject summary); + void privateGetAddressBookGetSignal(OAIObject summary); + void privateGetCurrentDepositAddressGetSignal(OAIObject summary); + void privateGetDepositsGetSignal(OAIObject summary); + void privateGetEmailLanguageGetSignal(OAIObject summary); + void privateGetMarginsGetSignal(OAIObject summary); + void privateGetNewAnnouncementsGetSignal(OAIObject summary); + void privateGetOpenOrdersByCurrencyGetSignal(OAIObject summary); + void privateGetOpenOrdersByInstrumentGetSignal(OAIObject summary); + void privateGetOrderHistoryByCurrencyGetSignal(OAIObject summary); + void privateGetOrderHistoryByInstrumentGetSignal(OAIObject summary); + void privateGetOrderMarginByIdsGetSignal(OAIObject summary); + void privateGetOrderStateGetSignal(OAIObject summary); + void privateGetPositionGetSignal(OAIObject summary); + void privateGetPositionsGetSignal(OAIObject summary); + void privateGetSettlementHistoryByCurrencyGetSignal(OAIObject summary); + void privateGetSettlementHistoryByInstrumentGetSignal(OAIObject summary); + void privateGetSubaccountsGetSignal(OAIObject summary); + void privateGetTransfersGetSignal(OAIObject summary); + void privateGetUserTradesByCurrencyAndTimeGetSignal(OAIObject summary); + void privateGetUserTradesByCurrencyGetSignal(OAIObject summary); + void privateGetUserTradesByInstrumentAndTimeGetSignal(OAIObject summary); + void privateGetUserTradesByInstrumentGetSignal(OAIObject summary); + void privateGetUserTradesByOrderGetSignal(OAIObject summary); + void privateGetWithdrawalsGetSignal(OAIObject summary); + void privateRemoveFromAddressBookGetSignal(OAIObject summary); + void privateSellGetSignal(OAIObject summary); + void privateSetAnnouncementAsReadGetSignal(OAIObject summary); + void privateSetEmailForSubaccountGetSignal(OAIObject summary); + void privateSetEmailLanguageGetSignal(OAIObject summary); + void privateSetPasswordForSubaccountGetSignal(OAIObject summary); + void privateSubmitTransferToSubaccountGetSignal(OAIObject summary); + void privateSubmitTransferToUserGetSignal(OAIObject summary); + void privateToggleDepositAddressCreationGetSignal(OAIObject summary); + void privateToggleNotificationsFromSubaccountGetSignal(OAIObject summary); + void privateToggleSubaccountLoginGetSignal(OAIObject summary); + void privateWithdrawGetSignal(OAIObject summary); + + void privateAddToAddressBookGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateBuyGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateCancelAllByCurrencyGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateCancelAllByInstrumentGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateCancelAllGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateCancelGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateCancelTransferByIdGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateCancelWithdrawalGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateChangeSubaccountNameGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateClosePositionGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateCreateDepositAddressGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateCreateSubaccountGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateDisableTfaForSubaccountGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateDisableTfaWithRecoveryCodeGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateEditGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetAccountSummaryGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetAddressBookGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetCurrentDepositAddressGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetDepositsGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetEmailLanguageGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetMarginsGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetNewAnnouncementsGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetOpenOrdersByCurrencyGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetOpenOrdersByInstrumentGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetOrderHistoryByCurrencyGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetOrderHistoryByInstrumentGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetOrderMarginByIdsGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetOrderStateGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetPositionGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetPositionsGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetSettlementHistoryByCurrencyGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetSettlementHistoryByInstrumentGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetSubaccountsGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetTransfersGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetUserTradesByCurrencyAndTimeGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetUserTradesByCurrencyGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetUserTradesByInstrumentAndTimeGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetUserTradesByInstrumentGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetUserTradesByOrderGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetWithdrawalsGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateRemoveFromAddressBookGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateSellGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateSetAnnouncementAsReadGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateSetEmailForSubaccountGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateSetEmailLanguageGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateSetPasswordForSubaccountGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateSubmitTransferToSubaccountGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateSubmitTransferToUserGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateToggleDepositAddressCreationGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateToggleNotificationsFromSubaccountGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateToggleSubaccountLoginGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateWithdrawGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + + void privateAddToAddressBookGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateBuyGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCancelAllByCurrencyGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCancelAllByInstrumentGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCancelAllGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCancelGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCancelTransferByIdGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCancelWithdrawalGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateChangeSubaccountNameGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateClosePositionGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCreateDepositAddressGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCreateSubaccountGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateDisableTfaForSubaccountGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateDisableTfaWithRecoveryCodeGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateEditGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetAccountSummaryGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetAddressBookGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetCurrentDepositAddressGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetDepositsGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetEmailLanguageGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetMarginsGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetNewAnnouncementsGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetOpenOrdersByCurrencyGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetOpenOrdersByInstrumentGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetOrderHistoryByCurrencyGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetOrderHistoryByInstrumentGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetOrderMarginByIdsGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetOrderStateGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetPositionGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetPositionsGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetSettlementHistoryByCurrencyGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetSettlementHistoryByInstrumentGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetSubaccountsGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetTransfersGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetUserTradesByCurrencyAndTimeGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetUserTradesByCurrencyGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetUserTradesByInstrumentAndTimeGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetUserTradesByInstrumentGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetUserTradesByOrderGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetWithdrawalsGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateRemoveFromAddressBookGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSellGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSetAnnouncementAsReadGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSetEmailForSubaccountGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSetEmailLanguageGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSetPasswordForSubaccountGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSubmitTransferToSubaccountGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSubmitTransferToUserGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateToggleDepositAddressCreationGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateToggleNotificationsFromSubaccountGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateToggleSubaccountLoginGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateWithdrawGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + + void privateAddToAddressBookGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateBuyGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCancelAllByCurrencyGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCancelAllByInstrumentGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCancelAllGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCancelGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCancelTransferByIdGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCancelWithdrawalGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateChangeSubaccountNameGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateClosePositionGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCreateDepositAddressGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCreateSubaccountGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateDisableTfaForSubaccountGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateDisableTfaWithRecoveryCodeGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateEditGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetAccountSummaryGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetAddressBookGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetCurrentDepositAddressGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetDepositsGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetEmailLanguageGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetMarginsGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetNewAnnouncementsGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetOpenOrdersByCurrencyGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetOpenOrdersByInstrumentGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetOrderHistoryByCurrencyGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetOrderHistoryByInstrumentGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetOrderMarginByIdsGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetOrderStateGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetPositionGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetPositionsGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetSettlementHistoryByCurrencyGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetSettlementHistoryByInstrumentGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetSubaccountsGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetTransfersGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetUserTradesByCurrencyAndTimeGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetUserTradesByCurrencyGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetUserTradesByInstrumentAndTimeGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetUserTradesByInstrumentGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetUserTradesByOrderGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetWithdrawalsGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateRemoveFromAddressBookGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSellGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSetAnnouncementAsReadGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSetEmailForSubaccountGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSetEmailLanguageGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSetPasswordForSubaccountGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSubmitTransferToSubaccountGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSubmitTransferToUserGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateToggleDepositAddressCreationGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateToggleNotificationsFromSubaccountGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateToggleSubaccountLoginGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateWithdrawGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + +}; + +} +#endif diff --git a/cpp-qt5-client/client/OAIPublicApi.cpp b/cpp-qt5-client/client/OAIPublicApi.cpp new file mode 100644 index 0000000..6b5daf7 --- /dev/null +++ b/cpp-qt5-client/client/OAIPublicApi.cpp @@ -0,0 +1,1628 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "OAIPublicApi.h" +#include "OAIHelpers.h" + +#include +#include + +namespace OpenAPI { + +OAIPublicApi::OAIPublicApi() : basePath("/api/v2"), + host("www.deribit.com") { + +} + +OAIPublicApi::~OAIPublicApi() { + +} + +OAIPublicApi::OAIPublicApi(const QString& host, const QString& basePath) { + this->host = host; + this->basePath = basePath; +} + +void OAIPublicApi::setBasePath(const QString& basePath){ + this->basePath = basePath; +} + +void OAIPublicApi::setHost(const QString& host){ + this->host = host; +} + +void OAIPublicApi::addHeaders(const QString& key, const QString& value){ + defaultHeaders.insert(key, value); +} + + +void +OAIPublicApi::publicAuthGet(const QString& grant_type, const QString& username, const QString& password, const QString& client_id, const QString& client_secret, const QString& refresh_token, const QString& timestamp, const QString& signature, const QString& nonce, const QString& state, const QString& scope) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/auth"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("grant_type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(grant_type))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("username")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(username))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("password")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(password))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("client_id")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(client_id))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("client_secret")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(client_secret))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("refresh_token")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(refresh_token))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(timestamp))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("signature")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(signature))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("nonce")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(nonce))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("state")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(state))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("scope")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(scope))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPublicApi::publicAuthGetCallback); + + worker->execute(&input); +} + +void +OAIPublicApi::publicAuthGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicAuthGetSignal(output); + emit publicAuthGetSignalFull(worker, output); + } else { + emit publicAuthGetSignalE(output, error_type, error_str); + emit publicAuthGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPublicApi::publicGetAnnouncementsGet() { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_announcements"); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPublicApi::publicGetAnnouncementsGetCallback); + + worker->execute(&input); +} + +void +OAIPublicApi::publicGetAnnouncementsGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetAnnouncementsGetSignal(output); + emit publicGetAnnouncementsGetSignalFull(worker, output); + } else { + emit publicGetAnnouncementsGetSignalE(output, error_type, error_str); + emit publicGetAnnouncementsGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPublicApi::publicGetBookSummaryByCurrencyGet(const QString& currency, const QString& kind) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_book_summary_by_currency"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("kind")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(kind))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPublicApi::publicGetBookSummaryByCurrencyGetCallback); + + worker->execute(&input); +} + +void +OAIPublicApi::publicGetBookSummaryByCurrencyGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetBookSummaryByCurrencyGetSignal(output); + emit publicGetBookSummaryByCurrencyGetSignalFull(worker, output); + } else { + emit publicGetBookSummaryByCurrencyGetSignalE(output, error_type, error_str); + emit publicGetBookSummaryByCurrencyGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPublicApi::publicGetBookSummaryByInstrumentGet(const QString& instrument_name) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_book_summary_by_instrument"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPublicApi::publicGetBookSummaryByInstrumentGetCallback); + + worker->execute(&input); +} + +void +OAIPublicApi::publicGetBookSummaryByInstrumentGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetBookSummaryByInstrumentGetSignal(output); + emit publicGetBookSummaryByInstrumentGetSignalFull(worker, output); + } else { + emit publicGetBookSummaryByInstrumentGetSignalE(output, error_type, error_str); + emit publicGetBookSummaryByInstrumentGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPublicApi::publicGetContractSizeGet(const QString& instrument_name) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_contract_size"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPublicApi::publicGetContractSizeGetCallback); + + worker->execute(&input); +} + +void +OAIPublicApi::publicGetContractSizeGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetContractSizeGetSignal(output); + emit publicGetContractSizeGetSignalFull(worker, output); + } else { + emit publicGetContractSizeGetSignalE(output, error_type, error_str); + emit publicGetContractSizeGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPublicApi::publicGetCurrenciesGet() { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_currencies"); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPublicApi::publicGetCurrenciesGetCallback); + + worker->execute(&input); +} + +void +OAIPublicApi::publicGetCurrenciesGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetCurrenciesGetSignal(output); + emit publicGetCurrenciesGetSignalFull(worker, output); + } else { + emit publicGetCurrenciesGetSignalE(output, error_type, error_str); + emit publicGetCurrenciesGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPublicApi::publicGetFundingChartDataGet(const QString& instrument_name, const QString& length) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_funding_chart_data"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("length")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(length))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPublicApi::publicGetFundingChartDataGetCallback); + + worker->execute(&input); +} + +void +OAIPublicApi::publicGetFundingChartDataGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetFundingChartDataGetSignal(output); + emit publicGetFundingChartDataGetSignalFull(worker, output); + } else { + emit publicGetFundingChartDataGetSignalE(output, error_type, error_str); + emit publicGetFundingChartDataGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPublicApi::publicGetHistoricalVolatilityGet(const QString& currency) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_historical_volatility"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPublicApi::publicGetHistoricalVolatilityGetCallback); + + worker->execute(&input); +} + +void +OAIPublicApi::publicGetHistoricalVolatilityGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetHistoricalVolatilityGetSignal(output); + emit publicGetHistoricalVolatilityGetSignalFull(worker, output); + } else { + emit publicGetHistoricalVolatilityGetSignalE(output, error_type, error_str); + emit publicGetHistoricalVolatilityGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPublicApi::publicGetIndexGet(const QString& currency) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_index"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPublicApi::publicGetIndexGetCallback); + + worker->execute(&input); +} + +void +OAIPublicApi::publicGetIndexGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetIndexGetSignal(output); + emit publicGetIndexGetSignalFull(worker, output); + } else { + emit publicGetIndexGetSignalE(output, error_type, error_str); + emit publicGetIndexGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPublicApi::publicGetInstrumentsGet(const QString& currency, const QString& kind, const bool& expired) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_instruments"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("kind")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(kind))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("expired")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(expired))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPublicApi::publicGetInstrumentsGetCallback); + + worker->execute(&input); +} + +void +OAIPublicApi::publicGetInstrumentsGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetInstrumentsGetSignal(output); + emit publicGetInstrumentsGetSignalFull(worker, output); + } else { + emit publicGetInstrumentsGetSignalE(output, error_type, error_str); + emit publicGetInstrumentsGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPublicApi::publicGetLastSettlementsByCurrencyGet(const QString& currency, const QString& type, const qint32& count, const QString& continuation, const qint32& search_start_timestamp) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_last_settlements_by_currency"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("continuation")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(continuation))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("search_start_timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(search_start_timestamp))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPublicApi::publicGetLastSettlementsByCurrencyGetCallback); + + worker->execute(&input); +} + +void +OAIPublicApi::publicGetLastSettlementsByCurrencyGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetLastSettlementsByCurrencyGetSignal(output); + emit publicGetLastSettlementsByCurrencyGetSignalFull(worker, output); + } else { + emit publicGetLastSettlementsByCurrencyGetSignalE(output, error_type, error_str); + emit publicGetLastSettlementsByCurrencyGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPublicApi::publicGetLastSettlementsByInstrumentGet(const QString& instrument_name, const QString& type, const qint32& count, const QString& continuation, const qint32& search_start_timestamp) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_last_settlements_by_instrument"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("continuation")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(continuation))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("search_start_timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(search_start_timestamp))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPublicApi::publicGetLastSettlementsByInstrumentGetCallback); + + worker->execute(&input); +} + +void +OAIPublicApi::publicGetLastSettlementsByInstrumentGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetLastSettlementsByInstrumentGetSignal(output); + emit publicGetLastSettlementsByInstrumentGetSignalFull(worker, output); + } else { + emit publicGetLastSettlementsByInstrumentGetSignalE(output, error_type, error_str); + emit publicGetLastSettlementsByInstrumentGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPublicApi::publicGetLastTradesByCurrencyAndTimeGet(const QString& currency, const qint32& start_timestamp, const qint32& end_timestamp, const QString& kind, const qint32& count, const bool& include_old, const QString& sorting) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_last_trades_by_currency_and_time"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("kind")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(kind))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("start_timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(start_timestamp))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("end_timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(end_timestamp))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("include_old")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(include_old))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sorting")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sorting))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPublicApi::publicGetLastTradesByCurrencyAndTimeGetCallback); + + worker->execute(&input); +} + +void +OAIPublicApi::publicGetLastTradesByCurrencyAndTimeGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetLastTradesByCurrencyAndTimeGetSignal(output); + emit publicGetLastTradesByCurrencyAndTimeGetSignalFull(worker, output); + } else { + emit publicGetLastTradesByCurrencyAndTimeGetSignalE(output, error_type, error_str); + emit publicGetLastTradesByCurrencyAndTimeGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPublicApi::publicGetLastTradesByCurrencyGet(const QString& currency, const QString& kind, const QString& start_id, const QString& end_id, const qint32& count, const bool& include_old, const QString& sorting) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_last_trades_by_currency"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("kind")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(kind))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("start_id")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(start_id))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("end_id")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(end_id))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("include_old")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(include_old))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sorting")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sorting))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPublicApi::publicGetLastTradesByCurrencyGetCallback); + + worker->execute(&input); +} + +void +OAIPublicApi::publicGetLastTradesByCurrencyGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetLastTradesByCurrencyGetSignal(output); + emit publicGetLastTradesByCurrencyGetSignalFull(worker, output); + } else { + emit publicGetLastTradesByCurrencyGetSignalE(output, error_type, error_str); + emit publicGetLastTradesByCurrencyGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPublicApi::publicGetLastTradesByInstrumentAndTimeGet(const QString& instrument_name, const qint32& start_timestamp, const qint32& end_timestamp, const qint32& count, const bool& include_old, const QString& sorting) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_last_trades_by_instrument_and_time"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("start_timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(start_timestamp))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("end_timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(end_timestamp))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("include_old")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(include_old))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sorting")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sorting))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPublicApi::publicGetLastTradesByInstrumentAndTimeGetCallback); + + worker->execute(&input); +} + +void +OAIPublicApi::publicGetLastTradesByInstrumentAndTimeGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetLastTradesByInstrumentAndTimeGetSignal(output); + emit publicGetLastTradesByInstrumentAndTimeGetSignalFull(worker, output); + } else { + emit publicGetLastTradesByInstrumentAndTimeGetSignalE(output, error_type, error_str); + emit publicGetLastTradesByInstrumentAndTimeGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPublicApi::publicGetLastTradesByInstrumentGet(const QString& instrument_name, const qint32& start_seq, const qint32& end_seq, const qint32& count, const bool& include_old, const QString& sorting) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_last_trades_by_instrument"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("start_seq")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(start_seq))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("end_seq")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(end_seq))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("include_old")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(include_old))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sorting")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sorting))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPublicApi::publicGetLastTradesByInstrumentGetCallback); + + worker->execute(&input); +} + +void +OAIPublicApi::publicGetLastTradesByInstrumentGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetLastTradesByInstrumentGetSignal(output); + emit publicGetLastTradesByInstrumentGetSignalFull(worker, output); + } else { + emit publicGetLastTradesByInstrumentGetSignalE(output, error_type, error_str); + emit publicGetLastTradesByInstrumentGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPublicApi::publicGetOrderBookGet(const QString& instrument_name, const double& depth) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_order_book"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("depth")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(depth))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPublicApi::publicGetOrderBookGetCallback); + + worker->execute(&input); +} + +void +OAIPublicApi::publicGetOrderBookGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetOrderBookGetSignal(output); + emit publicGetOrderBookGetSignalFull(worker, output); + } else { + emit publicGetOrderBookGetSignalE(output, error_type, error_str); + emit publicGetOrderBookGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPublicApi::publicGetTimeGet() { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_time"); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPublicApi::publicGetTimeGetCallback); + + worker->execute(&input); +} + +void +OAIPublicApi::publicGetTimeGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetTimeGetSignal(output); + emit publicGetTimeGetSignalFull(worker, output); + } else { + emit publicGetTimeGetSignalE(output, error_type, error_str); + emit publicGetTimeGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPublicApi::publicGetTradeVolumesGet() { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_trade_volumes"); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPublicApi::publicGetTradeVolumesGetCallback); + + worker->execute(&input); +} + +void +OAIPublicApi::publicGetTradeVolumesGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetTradeVolumesGetSignal(output); + emit publicGetTradeVolumesGetSignalFull(worker, output); + } else { + emit publicGetTradeVolumesGetSignalE(output, error_type, error_str); + emit publicGetTradeVolumesGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPublicApi::publicGetTradingviewChartDataGet(const QString& instrument_name, const qint32& start_timestamp, const qint32& end_timestamp) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_tradingview_chart_data"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("start_timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(start_timestamp))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("end_timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(end_timestamp))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPublicApi::publicGetTradingviewChartDataGetCallback); + + worker->execute(&input); +} + +void +OAIPublicApi::publicGetTradingviewChartDataGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetTradingviewChartDataGetSignal(output); + emit publicGetTradingviewChartDataGetSignalFull(worker, output); + } else { + emit publicGetTradingviewChartDataGetSignalE(output, error_type, error_str); + emit publicGetTradingviewChartDataGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPublicApi::publicTestGet(const QString& expected_result) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/test"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("expected_result")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(expected_result))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPublicApi::publicTestGetCallback); + + worker->execute(&input); +} + +void +OAIPublicApi::publicTestGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicTestGetSignal(output); + emit publicTestGetSignalFull(worker, output); + } else { + emit publicTestGetSignalE(output, error_type, error_str); + emit publicTestGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPublicApi::publicTickerGet(const QString& instrument_name) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/ticker"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPublicApi::publicTickerGetCallback); + + worker->execute(&input); +} + +void +OAIPublicApi::publicTickerGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicTickerGetSignal(output); + emit publicTickerGetSignalFull(worker, output); + } else { + emit publicTickerGetSignalE(output, error_type, error_str); + emit publicTickerGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIPublicApi::publicValidateFieldGet(const QString& field, const QString& value, const QString& value2) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/validate_field"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("field")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(field))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("value")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(value))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("value2")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(value2))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIPublicApi::publicValidateFieldGetCallback); + + worker->execute(&input); +} + +void +OAIPublicApi::publicValidateFieldGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicValidateFieldGetSignal(output); + emit publicValidateFieldGetSignalFull(worker, output); + } else { + emit publicValidateFieldGetSignalE(output, error_type, error_str); + emit publicValidateFieldGetSignalEFull(worker, error_type, error_str); + } +} + + +} diff --git a/cpp-qt5-client/client/OAIPublicApi.h b/cpp-qt5-client/client/OAIPublicApi.h new file mode 100644 index 0000000..c72e9a1 --- /dev/null +++ b/cpp-qt5-client/client/OAIPublicApi.h @@ -0,0 +1,189 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#ifndef OAI_OAIPublicApi_H +#define OAI_OAIPublicApi_H + +#include "OAIHttpRequest.h" + +#include "OAIObject.h" +#include + +#include + +namespace OpenAPI { + +class OAIPublicApi: public QObject { + Q_OBJECT + +public: + OAIPublicApi(); + OAIPublicApi(const QString& host, const QString& basePath); + ~OAIPublicApi(); + + void setBasePath(const QString& basePath); + void setHost(const QString& host); + void addHeaders(const QString& key, const QString& value); + + void publicAuthGet(const QString& grant_type, const QString& username, const QString& password, const QString& client_id, const QString& client_secret, const QString& refresh_token, const QString& timestamp, const QString& signature, const QString& nonce, const QString& state, const QString& scope); + void publicGetAnnouncementsGet(); + void publicGetBookSummaryByCurrencyGet(const QString& currency, const QString& kind); + void publicGetBookSummaryByInstrumentGet(const QString& instrument_name); + void publicGetContractSizeGet(const QString& instrument_name); + void publicGetCurrenciesGet(); + void publicGetFundingChartDataGet(const QString& instrument_name, const QString& length); + void publicGetHistoricalVolatilityGet(const QString& currency); + void publicGetIndexGet(const QString& currency); + void publicGetInstrumentsGet(const QString& currency, const QString& kind, const bool& expired); + void publicGetLastSettlementsByCurrencyGet(const QString& currency, const QString& type, const qint32& count, const QString& continuation, const qint32& search_start_timestamp); + void publicGetLastSettlementsByInstrumentGet(const QString& instrument_name, const QString& type, const qint32& count, const QString& continuation, const qint32& search_start_timestamp); + void publicGetLastTradesByCurrencyAndTimeGet(const QString& currency, const qint32& start_timestamp, const qint32& end_timestamp, const QString& kind, const qint32& count, const bool& include_old, const QString& sorting); + void publicGetLastTradesByCurrencyGet(const QString& currency, const QString& kind, const QString& start_id, const QString& end_id, const qint32& count, const bool& include_old, const QString& sorting); + void publicGetLastTradesByInstrumentAndTimeGet(const QString& instrument_name, const qint32& start_timestamp, const qint32& end_timestamp, const qint32& count, const bool& include_old, const QString& sorting); + void publicGetLastTradesByInstrumentGet(const QString& instrument_name, const qint32& start_seq, const qint32& end_seq, const qint32& count, const bool& include_old, const QString& sorting); + void publicGetOrderBookGet(const QString& instrument_name, const double& depth); + void publicGetTimeGet(); + void publicGetTradeVolumesGet(); + void publicGetTradingviewChartDataGet(const QString& instrument_name, const qint32& start_timestamp, const qint32& end_timestamp); + void publicTestGet(const QString& expected_result); + void publicTickerGet(const QString& instrument_name); + void publicValidateFieldGet(const QString& field, const QString& value, const QString& value2); + +private: + QString basePath; + QString host; + QMap defaultHeaders; + void publicAuthGetCallback (OAIHttpRequestWorker * worker); + void publicGetAnnouncementsGetCallback (OAIHttpRequestWorker * worker); + void publicGetBookSummaryByCurrencyGetCallback (OAIHttpRequestWorker * worker); + void publicGetBookSummaryByInstrumentGetCallback (OAIHttpRequestWorker * worker); + void publicGetContractSizeGetCallback (OAIHttpRequestWorker * worker); + void publicGetCurrenciesGetCallback (OAIHttpRequestWorker * worker); + void publicGetFundingChartDataGetCallback (OAIHttpRequestWorker * worker); + void publicGetHistoricalVolatilityGetCallback (OAIHttpRequestWorker * worker); + void publicGetIndexGetCallback (OAIHttpRequestWorker * worker); + void publicGetInstrumentsGetCallback (OAIHttpRequestWorker * worker); + void publicGetLastSettlementsByCurrencyGetCallback (OAIHttpRequestWorker * worker); + void publicGetLastSettlementsByInstrumentGetCallback (OAIHttpRequestWorker * worker); + void publicGetLastTradesByCurrencyAndTimeGetCallback (OAIHttpRequestWorker * worker); + void publicGetLastTradesByCurrencyGetCallback (OAIHttpRequestWorker * worker); + void publicGetLastTradesByInstrumentAndTimeGetCallback (OAIHttpRequestWorker * worker); + void publicGetLastTradesByInstrumentGetCallback (OAIHttpRequestWorker * worker); + void publicGetOrderBookGetCallback (OAIHttpRequestWorker * worker); + void publicGetTimeGetCallback (OAIHttpRequestWorker * worker); + void publicGetTradeVolumesGetCallback (OAIHttpRequestWorker * worker); + void publicGetTradingviewChartDataGetCallback (OAIHttpRequestWorker * worker); + void publicTestGetCallback (OAIHttpRequestWorker * worker); + void publicTickerGetCallback (OAIHttpRequestWorker * worker); + void publicValidateFieldGetCallback (OAIHttpRequestWorker * worker); + +signals: + void publicAuthGetSignal(OAIObject summary); + void publicGetAnnouncementsGetSignal(OAIObject summary); + void publicGetBookSummaryByCurrencyGetSignal(OAIObject summary); + void publicGetBookSummaryByInstrumentGetSignal(OAIObject summary); + void publicGetContractSizeGetSignal(OAIObject summary); + void publicGetCurrenciesGetSignal(OAIObject summary); + void publicGetFundingChartDataGetSignal(OAIObject summary); + void publicGetHistoricalVolatilityGetSignal(OAIObject summary); + void publicGetIndexGetSignal(OAIObject summary); + void publicGetInstrumentsGetSignal(OAIObject summary); + void publicGetLastSettlementsByCurrencyGetSignal(OAIObject summary); + void publicGetLastSettlementsByInstrumentGetSignal(OAIObject summary); + void publicGetLastTradesByCurrencyAndTimeGetSignal(OAIObject summary); + void publicGetLastTradesByCurrencyGetSignal(OAIObject summary); + void publicGetLastTradesByInstrumentAndTimeGetSignal(OAIObject summary); + void publicGetLastTradesByInstrumentGetSignal(OAIObject summary); + void publicGetOrderBookGetSignal(OAIObject summary); + void publicGetTimeGetSignal(OAIObject summary); + void publicGetTradeVolumesGetSignal(OAIObject summary); + void publicGetTradingviewChartDataGetSignal(OAIObject summary); + void publicTestGetSignal(OAIObject summary); + void publicTickerGetSignal(OAIObject summary); + void publicValidateFieldGetSignal(OAIObject summary); + + void publicAuthGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetAnnouncementsGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetBookSummaryByCurrencyGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetBookSummaryByInstrumentGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetContractSizeGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetCurrenciesGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetFundingChartDataGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetHistoricalVolatilityGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetIndexGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetInstrumentsGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetLastSettlementsByCurrencyGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetLastSettlementsByInstrumentGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetLastTradesByCurrencyAndTimeGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetLastTradesByCurrencyGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetLastTradesByInstrumentAndTimeGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetLastTradesByInstrumentGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetOrderBookGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetTimeGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetTradeVolumesGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicGetTradingviewChartDataGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicTestGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicTickerGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicValidateFieldGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + + void publicAuthGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetAnnouncementsGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetBookSummaryByCurrencyGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetBookSummaryByInstrumentGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetContractSizeGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetCurrenciesGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetFundingChartDataGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetHistoricalVolatilityGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetIndexGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetInstrumentsGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetLastSettlementsByCurrencyGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetLastSettlementsByInstrumentGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetLastTradesByCurrencyAndTimeGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetLastTradesByCurrencyGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetLastTradesByInstrumentAndTimeGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetLastTradesByInstrumentGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetOrderBookGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetTimeGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetTradeVolumesGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetTradingviewChartDataGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicTestGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicTickerGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicValidateFieldGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + + void publicAuthGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetAnnouncementsGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetBookSummaryByCurrencyGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetBookSummaryByInstrumentGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetContractSizeGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetCurrenciesGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetFundingChartDataGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetHistoricalVolatilityGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetIndexGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetInstrumentsGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetLastSettlementsByCurrencyGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetLastSettlementsByInstrumentGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetLastTradesByCurrencyAndTimeGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetLastTradesByCurrencyGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetLastTradesByInstrumentAndTimeGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetLastTradesByInstrumentGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetOrderBookGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetTimeGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetTradeVolumesGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicGetTradingviewChartDataGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicTestGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicTickerGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicValidateFieldGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + +}; + +} +#endif diff --git a/cpp-qt5-client/client/OAIPublic_trade.cpp b/cpp-qt5-client/client/OAIPublic_trade.cpp new file mode 100644 index 0000000..e298b4a --- /dev/null +++ b/cpp-qt5-client/client/OAIPublic_trade.cpp @@ -0,0 +1,303 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include "OAIPublic_trade.h" + +#include "OAIHelpers.h" + +#include +#include +#include +#include + +namespace OpenAPI { + +OAIPublic_trade::OAIPublic_trade(QString json) { + this->init(); + this->fromJson(json); +} + +OAIPublic_trade::OAIPublic_trade() { + this->init(); +} + +OAIPublic_trade::~OAIPublic_trade() { + +} + +void +OAIPublic_trade::init() { + + m_direction_isSet = false; + m_direction_isValid = false; + + m_tick_direction_isSet = false; + m_tick_direction_isValid = false; + + m_timestamp_isSet = false; + m_timestamp_isValid = false; + + m_price_isSet = false; + m_price_isValid = false; + + m_trade_seq_isSet = false; + m_trade_seq_isValid = false; + + m_trade_id_isSet = false; + m_trade_id_isValid = false; + + m_iv_isSet = false; + m_iv_isValid = false; + + m_index_price_isSet = false; + m_index_price_isValid = false; + + m_amount_isSet = false; + m_amount_isValid = false; + + m_instrument_name_isSet = false; + m_instrument_name_isValid = false; + } + +void +OAIPublic_trade::fromJson(QString jsonString) { + QByteArray array (jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void +OAIPublic_trade::fromJsonObject(QJsonObject json) { + + m_direction_isValid = ::OpenAPI::fromJsonValue(direction, json[QString("direction")]); + + + m_tick_direction_isValid = ::OpenAPI::fromJsonValue(tick_direction, json[QString("tick_direction")]); + + + m_timestamp_isValid = ::OpenAPI::fromJsonValue(timestamp, json[QString("timestamp")]); + + + m_price_isValid = ::OpenAPI::fromJsonValue(price, json[QString("price")]); + + + m_trade_seq_isValid = ::OpenAPI::fromJsonValue(trade_seq, json[QString("trade_seq")]); + + + m_trade_id_isValid = ::OpenAPI::fromJsonValue(trade_id, json[QString("trade_id")]); + + + m_iv_isValid = ::OpenAPI::fromJsonValue(iv, json[QString("iv")]); + + + m_index_price_isValid = ::OpenAPI::fromJsonValue(index_price, json[QString("index_price")]); + + + m_amount_isValid = ::OpenAPI::fromJsonValue(amount, json[QString("amount")]); + + + m_instrument_name_isValid = ::OpenAPI::fromJsonValue(instrument_name, json[QString("instrument_name")]); + + +} + +QString +OAIPublic_trade::asJson () const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject +OAIPublic_trade::asJsonObject() const { + QJsonObject obj; + if(m_direction_isSet){ + obj.insert(QString("direction"), ::OpenAPI::toJsonValue(direction)); + } + if(m_tick_direction_isSet){ + obj.insert(QString("tick_direction"), ::OpenAPI::toJsonValue(tick_direction)); + } + if(m_timestamp_isSet){ + obj.insert(QString("timestamp"), ::OpenAPI::toJsonValue(timestamp)); + } + if(m_price_isSet){ + obj.insert(QString("price"), ::OpenAPI::toJsonValue(price)); + } + if(m_trade_seq_isSet){ + obj.insert(QString("trade_seq"), ::OpenAPI::toJsonValue(trade_seq)); + } + if(m_trade_id_isSet){ + obj.insert(QString("trade_id"), ::OpenAPI::toJsonValue(trade_id)); + } + if(m_iv_isSet){ + obj.insert(QString("iv"), ::OpenAPI::toJsonValue(iv)); + } + if(m_index_price_isSet){ + obj.insert(QString("index_price"), ::OpenAPI::toJsonValue(index_price)); + } + if(m_amount_isSet){ + obj.insert(QString("amount"), ::OpenAPI::toJsonValue(amount)); + } + if(m_instrument_name_isSet){ + obj.insert(QString("instrument_name"), ::OpenAPI::toJsonValue(instrument_name)); + } + return obj; +} + + +QString +OAIPublic_trade::getDirection() const { + return direction; +} +void +OAIPublic_trade::setDirection(const QString &direction) { + this->direction = direction; + this->m_direction_isSet = true; +} + + +qint32 +OAIPublic_trade::getTickDirection() const { + return tick_direction; +} +void +OAIPublic_trade::setTickDirection(const qint32 &tick_direction) { + this->tick_direction = tick_direction; + this->m_tick_direction_isSet = true; +} + + +qint32 +OAIPublic_trade::getTimestamp() const { + return timestamp; +} +void +OAIPublic_trade::setTimestamp(const qint32 ×tamp) { + this->timestamp = timestamp; + this->m_timestamp_isSet = true; +} + + +double +OAIPublic_trade::getPrice() const { + return price; +} +void +OAIPublic_trade::setPrice(const double &price) { + this->price = price; + this->m_price_isSet = true; +} + + +qint32 +OAIPublic_trade::getTradeSeq() const { + return trade_seq; +} +void +OAIPublic_trade::setTradeSeq(const qint32 &trade_seq) { + this->trade_seq = trade_seq; + this->m_trade_seq_isSet = true; +} + + +QString +OAIPublic_trade::getTradeId() const { + return trade_id; +} +void +OAIPublic_trade::setTradeId(const QString &trade_id) { + this->trade_id = trade_id; + this->m_trade_id_isSet = true; +} + + +double +OAIPublic_trade::getIv() const { + return iv; +} +void +OAIPublic_trade::setIv(const double &iv) { + this->iv = iv; + this->m_iv_isSet = true; +} + + +double +OAIPublic_trade::getIndexPrice() const { + return index_price; +} +void +OAIPublic_trade::setIndexPrice(const double &index_price) { + this->index_price = index_price; + this->m_index_price_isSet = true; +} + + +double +OAIPublic_trade::getAmount() const { + return amount; +} +void +OAIPublic_trade::setAmount(const double &amount) { + this->amount = amount; + this->m_amount_isSet = true; +} + + +QString +OAIPublic_trade::getInstrumentName() const { + return instrument_name; +} +void +OAIPublic_trade::setInstrumentName(const QString &instrument_name) { + this->instrument_name = instrument_name; + this->m_instrument_name_isSet = true; +} + +bool +OAIPublic_trade::isSet() const { + bool isObjectUpdated = false; + do{ + if(m_direction_isSet){ isObjectUpdated = true; break;} + + if(m_tick_direction_isSet){ isObjectUpdated = true; break;} + + if(m_timestamp_isSet){ isObjectUpdated = true; break;} + + if(m_price_isSet){ isObjectUpdated = true; break;} + + if(m_trade_seq_isSet){ isObjectUpdated = true; break;} + + if(m_trade_id_isSet){ isObjectUpdated = true; break;} + + if(m_iv_isSet){ isObjectUpdated = true; break;} + + if(m_index_price_isSet){ isObjectUpdated = true; break;} + + if(m_amount_isSet){ isObjectUpdated = true; break;} + + if(m_instrument_name_isSet){ isObjectUpdated = true; break;} + }while(false); + return isObjectUpdated; +} + +bool +OAIPublic_trade::isValid() const { + // only required properties are required for the object to be considered valid + return m_direction_isValid && m_tick_direction_isValid && m_timestamp_isValid && m_price_isValid && m_trade_seq_isValid && m_trade_id_isValid && m_index_price_isValid && m_amount_isValid && m_instrument_name_isValid && true; +} + +} + diff --git a/cpp-qt5-client/client/OAIPublic_trade.h b/cpp-qt5-client/client/OAIPublic_trade.h new file mode 100644 index 0000000..2df384d --- /dev/null +++ b/cpp-qt5-client/client/OAIPublic_trade.h @@ -0,0 +1,135 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OAIPublic_trade.h + * + * + */ + +#ifndef OAIPublic_trade_H +#define OAIPublic_trade_H + +#include + + +#include + +#include "OAIObject.h" +#include "OAIEnum.h" + +namespace OpenAPI { + +class OAIPublic_trade: public OAIObject { +public: + OAIPublic_trade(); + OAIPublic_trade(QString json); + ~OAIPublic_trade() override; + + QString asJson () const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + + QString getDirection() const; + void setDirection(const QString &direction); + + + qint32 getTickDirection() const; + void setTickDirection(const qint32 &tick_direction); + + + qint32 getTimestamp() const; + void setTimestamp(const qint32 ×tamp); + + + double getPrice() const; + void setPrice(const double &price); + + + qint32 getTradeSeq() const; + void setTradeSeq(const qint32 &trade_seq); + + + QString getTradeId() const; + void setTradeId(const QString &trade_id); + + + double getIv() const; + void setIv(const double &iv); + + + double getIndexPrice() const; + void setIndexPrice(const double &index_price); + + + double getAmount() const; + void setAmount(const double &amount); + + + QString getInstrumentName() const; + void setInstrumentName(const QString &instrument_name); + + + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void init(); + + QString direction; + bool m_direction_isSet; + bool m_direction_isValid; + + qint32 tick_direction; + bool m_tick_direction_isSet; + bool m_tick_direction_isValid; + + qint32 timestamp; + bool m_timestamp_isSet; + bool m_timestamp_isValid; + + double price; + bool m_price_isSet; + bool m_price_isValid; + + qint32 trade_seq; + bool m_trade_seq_isSet; + bool m_trade_seq_isValid; + + QString trade_id; + bool m_trade_id_isSet; + bool m_trade_id_isValid; + + double iv; + bool m_iv_isSet; + bool m_iv_isValid; + + double index_price; + bool m_index_price_isSet; + bool m_index_price_isValid; + + double amount; + bool m_amount_isSet; + bool m_amount_isValid; + + QString instrument_name; + bool m_instrument_name_isSet; + bool m_instrument_name_isValid; + + }; + +} + +#endif // OAIPublic_trade_H diff --git a/cpp-qt5-client/client/OAISettlement.cpp b/cpp-qt5-client/client/OAISettlement.cpp new file mode 100644 index 0000000..be48438 --- /dev/null +++ b/cpp-qt5-client/client/OAISettlement.cpp @@ -0,0 +1,391 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include "OAISettlement.h" + +#include "OAIHelpers.h" + +#include +#include +#include +#include + +namespace OpenAPI { + +OAISettlement::OAISettlement(QString json) { + this->init(); + this->fromJson(json); +} + +OAISettlement::OAISettlement() { + this->init(); +} + +OAISettlement::~OAISettlement() { + +} + +void +OAISettlement::init() { + + m_session_profit_loss_isSet = false; + m_session_profit_loss_isValid = false; + + m_mark_price_isSet = false; + m_mark_price_isValid = false; + + m_funding_isSet = false; + m_funding_isValid = false; + + m_socialized_isSet = false; + m_socialized_isValid = false; + + m_session_bankrupcy_isSet = false; + m_session_bankrupcy_isValid = false; + + m_timestamp_isSet = false; + m_timestamp_isValid = false; + + m_profit_loss_isSet = false; + m_profit_loss_isValid = false; + + m_funded_isSet = false; + m_funded_isValid = false; + + m_index_price_isSet = false; + m_index_price_isValid = false; + + m_session_tax_isSet = false; + m_session_tax_isValid = false; + + m_session_tax_rate_isSet = false; + m_session_tax_rate_isValid = false; + + m_instrument_name_isSet = false; + m_instrument_name_isValid = false; + + m_position_isSet = false; + m_position_isValid = false; + + m_type_isSet = false; + m_type_isValid = false; + } + +void +OAISettlement::fromJson(QString jsonString) { + QByteArray array (jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void +OAISettlement::fromJsonObject(QJsonObject json) { + + m_session_profit_loss_isValid = ::OpenAPI::fromJsonValue(session_profit_loss, json[QString("session_profit_loss")]); + + + m_mark_price_isValid = ::OpenAPI::fromJsonValue(mark_price, json[QString("mark_price")]); + + + m_funding_isValid = ::OpenAPI::fromJsonValue(funding, json[QString("funding")]); + + + m_socialized_isValid = ::OpenAPI::fromJsonValue(socialized, json[QString("socialized")]); + + + m_session_bankrupcy_isValid = ::OpenAPI::fromJsonValue(session_bankrupcy, json[QString("session_bankrupcy")]); + + + m_timestamp_isValid = ::OpenAPI::fromJsonValue(timestamp, json[QString("timestamp")]); + + + m_profit_loss_isValid = ::OpenAPI::fromJsonValue(profit_loss, json[QString("profit_loss")]); + + + m_funded_isValid = ::OpenAPI::fromJsonValue(funded, json[QString("funded")]); + + + m_index_price_isValid = ::OpenAPI::fromJsonValue(index_price, json[QString("index_price")]); + + + m_session_tax_isValid = ::OpenAPI::fromJsonValue(session_tax, json[QString("session_tax")]); + + + m_session_tax_rate_isValid = ::OpenAPI::fromJsonValue(session_tax_rate, json[QString("session_tax_rate")]); + + + m_instrument_name_isValid = ::OpenAPI::fromJsonValue(instrument_name, json[QString("instrument_name")]); + + + m_position_isValid = ::OpenAPI::fromJsonValue(position, json[QString("position")]); + + + m_type_isValid = ::OpenAPI::fromJsonValue(type, json[QString("type")]); + + +} + +QString +OAISettlement::asJson () const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject +OAISettlement::asJsonObject() const { + QJsonObject obj; + if(m_session_profit_loss_isSet){ + obj.insert(QString("session_profit_loss"), ::OpenAPI::toJsonValue(session_profit_loss)); + } + if(m_mark_price_isSet){ + obj.insert(QString("mark_price"), ::OpenAPI::toJsonValue(mark_price)); + } + if(m_funding_isSet){ + obj.insert(QString("funding"), ::OpenAPI::toJsonValue(funding)); + } + if(m_socialized_isSet){ + obj.insert(QString("socialized"), ::OpenAPI::toJsonValue(socialized)); + } + if(m_session_bankrupcy_isSet){ + obj.insert(QString("session_bankrupcy"), ::OpenAPI::toJsonValue(session_bankrupcy)); + } + if(m_timestamp_isSet){ + obj.insert(QString("timestamp"), ::OpenAPI::toJsonValue(timestamp)); + } + if(m_profit_loss_isSet){ + obj.insert(QString("profit_loss"), ::OpenAPI::toJsonValue(profit_loss)); + } + if(m_funded_isSet){ + obj.insert(QString("funded"), ::OpenAPI::toJsonValue(funded)); + } + if(m_index_price_isSet){ + obj.insert(QString("index_price"), ::OpenAPI::toJsonValue(index_price)); + } + if(m_session_tax_isSet){ + obj.insert(QString("session_tax"), ::OpenAPI::toJsonValue(session_tax)); + } + if(m_session_tax_rate_isSet){ + obj.insert(QString("session_tax_rate"), ::OpenAPI::toJsonValue(session_tax_rate)); + } + if(m_instrument_name_isSet){ + obj.insert(QString("instrument_name"), ::OpenAPI::toJsonValue(instrument_name)); + } + if(m_position_isSet){ + obj.insert(QString("position"), ::OpenAPI::toJsonValue(position)); + } + if(m_type_isSet){ + obj.insert(QString("type"), ::OpenAPI::toJsonValue(type)); + } + return obj; +} + + +double +OAISettlement::getSessionProfitLoss() const { + return session_profit_loss; +} +void +OAISettlement::setSessionProfitLoss(const double &session_profit_loss) { + this->session_profit_loss = session_profit_loss; + this->m_session_profit_loss_isSet = true; +} + + +double +OAISettlement::getMarkPrice() const { + return mark_price; +} +void +OAISettlement::setMarkPrice(const double &mark_price) { + this->mark_price = mark_price; + this->m_mark_price_isSet = true; +} + + +double +OAISettlement::getFunding() const { + return funding; +} +void +OAISettlement::setFunding(const double &funding) { + this->funding = funding; + this->m_funding_isSet = true; +} + + +double +OAISettlement::getSocialized() const { + return socialized; +} +void +OAISettlement::setSocialized(const double &socialized) { + this->socialized = socialized; + this->m_socialized_isSet = true; +} + + +double +OAISettlement::getSessionBankrupcy() const { + return session_bankrupcy; +} +void +OAISettlement::setSessionBankrupcy(const double &session_bankrupcy) { + this->session_bankrupcy = session_bankrupcy; + this->m_session_bankrupcy_isSet = true; +} + + +qint32 +OAISettlement::getTimestamp() const { + return timestamp; +} +void +OAISettlement::setTimestamp(const qint32 ×tamp) { + this->timestamp = timestamp; + this->m_timestamp_isSet = true; +} + + +double +OAISettlement::getProfitLoss() const { + return profit_loss; +} +void +OAISettlement::setProfitLoss(const double &profit_loss) { + this->profit_loss = profit_loss; + this->m_profit_loss_isSet = true; +} + + +double +OAISettlement::getFunded() const { + return funded; +} +void +OAISettlement::setFunded(const double &funded) { + this->funded = funded; + this->m_funded_isSet = true; +} + + +double +OAISettlement::getIndexPrice() const { + return index_price; +} +void +OAISettlement::setIndexPrice(const double &index_price) { + this->index_price = index_price; + this->m_index_price_isSet = true; +} + + +double +OAISettlement::getSessionTax() const { + return session_tax; +} +void +OAISettlement::setSessionTax(const double &session_tax) { + this->session_tax = session_tax; + this->m_session_tax_isSet = true; +} + + +double +OAISettlement::getSessionTaxRate() const { + return session_tax_rate; +} +void +OAISettlement::setSessionTaxRate(const double &session_tax_rate) { + this->session_tax_rate = session_tax_rate; + this->m_session_tax_rate_isSet = true; +} + + +QString +OAISettlement::getInstrumentName() const { + return instrument_name; +} +void +OAISettlement::setInstrumentName(const QString &instrument_name) { + this->instrument_name = instrument_name; + this->m_instrument_name_isSet = true; +} + + +double +OAISettlement::getPosition() const { + return position; +} +void +OAISettlement::setPosition(const double &position) { + this->position = position; + this->m_position_isSet = true; +} + + +QString +OAISettlement::getType() const { + return type; +} +void +OAISettlement::setType(const QString &type) { + this->type = type; + this->m_type_isSet = true; +} + +bool +OAISettlement::isSet() const { + bool isObjectUpdated = false; + do{ + if(m_session_profit_loss_isSet){ isObjectUpdated = true; break;} + + if(m_mark_price_isSet){ isObjectUpdated = true; break;} + + if(m_funding_isSet){ isObjectUpdated = true; break;} + + if(m_socialized_isSet){ isObjectUpdated = true; break;} + + if(m_session_bankrupcy_isSet){ isObjectUpdated = true; break;} + + if(m_timestamp_isSet){ isObjectUpdated = true; break;} + + if(m_profit_loss_isSet){ isObjectUpdated = true; break;} + + if(m_funded_isSet){ isObjectUpdated = true; break;} + + if(m_index_price_isSet){ isObjectUpdated = true; break;} + + if(m_session_tax_isSet){ isObjectUpdated = true; break;} + + if(m_session_tax_rate_isSet){ isObjectUpdated = true; break;} + + if(m_instrument_name_isSet){ isObjectUpdated = true; break;} + + if(m_position_isSet){ isObjectUpdated = true; break;} + + if(m_type_isSet){ isObjectUpdated = true; break;} + }while(false); + return isObjectUpdated; +} + +bool +OAISettlement::isValid() const { + // only required properties are required for the object to be considered valid + return m_session_profit_loss_isValid && m_funding_isValid && m_timestamp_isValid && m_index_price_isValid && m_instrument_name_isValid && m_position_isValid && m_type_isValid && true; +} + +} + diff --git a/cpp-qt5-client/client/OAISettlement.h b/cpp-qt5-client/client/OAISettlement.h new file mode 100644 index 0000000..de45968 --- /dev/null +++ b/cpp-qt5-client/client/OAISettlement.h @@ -0,0 +1,167 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OAISettlement.h + * + * + */ + +#ifndef OAISettlement_H +#define OAISettlement_H + +#include + + +#include + +#include "OAIObject.h" +#include "OAIEnum.h" + +namespace OpenAPI { + +class OAISettlement: public OAIObject { +public: + OAISettlement(); + OAISettlement(QString json); + ~OAISettlement() override; + + QString asJson () const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + + double getSessionProfitLoss() const; + void setSessionProfitLoss(const double &session_profit_loss); + + + double getMarkPrice() const; + void setMarkPrice(const double &mark_price); + + + double getFunding() const; + void setFunding(const double &funding); + + + double getSocialized() const; + void setSocialized(const double &socialized); + + + double getSessionBankrupcy() const; + void setSessionBankrupcy(const double &session_bankrupcy); + + + qint32 getTimestamp() const; + void setTimestamp(const qint32 ×tamp); + + + double getProfitLoss() const; + void setProfitLoss(const double &profit_loss); + + + double getFunded() const; + void setFunded(const double &funded); + + + double getIndexPrice() const; + void setIndexPrice(const double &index_price); + + + double getSessionTax() const; + void setSessionTax(const double &session_tax); + + + double getSessionTaxRate() const; + void setSessionTaxRate(const double &session_tax_rate); + + + QString getInstrumentName() const; + void setInstrumentName(const QString &instrument_name); + + + double getPosition() const; + void setPosition(const double &position); + + + QString getType() const; + void setType(const QString &type); + + + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void init(); + + double session_profit_loss; + bool m_session_profit_loss_isSet; + bool m_session_profit_loss_isValid; + + double mark_price; + bool m_mark_price_isSet; + bool m_mark_price_isValid; + + double funding; + bool m_funding_isSet; + bool m_funding_isValid; + + double socialized; + bool m_socialized_isSet; + bool m_socialized_isValid; + + double session_bankrupcy; + bool m_session_bankrupcy_isSet; + bool m_session_bankrupcy_isValid; + + qint32 timestamp; + bool m_timestamp_isSet; + bool m_timestamp_isValid; + + double profit_loss; + bool m_profit_loss_isSet; + bool m_profit_loss_isValid; + + double funded; + bool m_funded_isSet; + bool m_funded_isValid; + + double index_price; + bool m_index_price_isSet; + bool m_index_price_isValid; + + double session_tax; + bool m_session_tax_isSet; + bool m_session_tax_isValid; + + double session_tax_rate; + bool m_session_tax_rate_isSet; + bool m_session_tax_rate_isValid; + + QString instrument_name; + bool m_instrument_name_isSet; + bool m_instrument_name_isValid; + + double position; + bool m_position_isSet; + bool m_position_isValid; + + QString type; + bool m_type_isSet; + bool m_type_isValid; + + }; + +} + +#endif // OAISettlement_H diff --git a/cpp-qt5-client/client/OAISupportingApi.cpp b/cpp-qt5-client/client/OAISupportingApi.cpp new file mode 100644 index 0000000..470a0c7 --- /dev/null +++ b/cpp-qt5-client/client/OAISupportingApi.cpp @@ -0,0 +1,147 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "OAISupportingApi.h" +#include "OAIHelpers.h" + +#include +#include + +namespace OpenAPI { + +OAISupportingApi::OAISupportingApi() : basePath("/api/v2"), + host("www.deribit.com") { + +} + +OAISupportingApi::~OAISupportingApi() { + +} + +OAISupportingApi::OAISupportingApi(const QString& host, const QString& basePath) { + this->host = host; + this->basePath = basePath; +} + +void OAISupportingApi::setBasePath(const QString& basePath){ + this->basePath = basePath; +} + +void OAISupportingApi::setHost(const QString& host){ + this->host = host; +} + +void OAISupportingApi::addHeaders(const QString& key, const QString& value){ + defaultHeaders.insert(key, value); +} + + +void +OAISupportingApi::publicGetTimeGet() { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/get_time"); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAISupportingApi::publicGetTimeGetCallback); + + worker->execute(&input); +} + +void +OAISupportingApi::publicGetTimeGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicGetTimeGetSignal(output); + emit publicGetTimeGetSignalFull(worker, output); + } else { + emit publicGetTimeGetSignalE(output, error_type, error_str); + emit publicGetTimeGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAISupportingApi::publicTestGet(const QString& expected_result) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/public/test"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("expected_result")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(expected_result))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAISupportingApi::publicTestGetCallback); + + worker->execute(&input); +} + +void +OAISupportingApi::publicTestGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit publicTestGetSignal(output); + emit publicTestGetSignalFull(worker, output); + } else { + emit publicTestGetSignalE(output, error_type, error_str); + emit publicTestGetSignalEFull(worker, error_type, error_str); + } +} + + +} diff --git a/cpp-qt5-client/client/OAISupportingApi.h b/cpp-qt5-client/client/OAISupportingApi.h new file mode 100644 index 0000000..837cf7e --- /dev/null +++ b/cpp-qt5-client/client/OAISupportingApi.h @@ -0,0 +1,63 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#ifndef OAI_OAISupportingApi_H +#define OAI_OAISupportingApi_H + +#include "OAIHttpRequest.h" + +#include "OAIObject.h" +#include + +#include + +namespace OpenAPI { + +class OAISupportingApi: public QObject { + Q_OBJECT + +public: + OAISupportingApi(); + OAISupportingApi(const QString& host, const QString& basePath); + ~OAISupportingApi(); + + void setBasePath(const QString& basePath); + void setHost(const QString& host); + void addHeaders(const QString& key, const QString& value); + + void publicGetTimeGet(); + void publicTestGet(const QString& expected_result); + +private: + QString basePath; + QString host; + QMap defaultHeaders; + void publicGetTimeGetCallback (OAIHttpRequestWorker * worker); + void publicTestGetCallback (OAIHttpRequestWorker * worker); + +signals: + void publicGetTimeGetSignal(OAIObject summary); + void publicTestGetSignal(OAIObject summary); + + void publicGetTimeGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void publicTestGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + + void publicGetTimeGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void publicTestGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + + void publicGetTimeGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void publicTestGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + +}; + +} +#endif diff --git a/cpp-qt5-client/client/OAITrades_volumes.cpp b/cpp-qt5-client/client/OAITrades_volumes.cpp new file mode 100644 index 0000000..9b420f6 --- /dev/null +++ b/cpp-qt5-client/client/OAITrades_volumes.cpp @@ -0,0 +1,171 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include "OAITrades_volumes.h" + +#include "OAIHelpers.h" + +#include +#include +#include +#include + +namespace OpenAPI { + +OAITrades_volumes::OAITrades_volumes(QString json) { + this->init(); + this->fromJson(json); +} + +OAITrades_volumes::OAITrades_volumes() { + this->init(); +} + +OAITrades_volumes::~OAITrades_volumes() { + +} + +void +OAITrades_volumes::init() { + + m_calls_volume_isSet = false; + m_calls_volume_isValid = false; + + m_puts_volume_isSet = false; + m_puts_volume_isValid = false; + + m_currency_pair_isSet = false; + m_currency_pair_isValid = false; + + m_futures_volume_isSet = false; + m_futures_volume_isValid = false; + } + +void +OAITrades_volumes::fromJson(QString jsonString) { + QByteArray array (jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void +OAITrades_volumes::fromJsonObject(QJsonObject json) { + + m_calls_volume_isValid = ::OpenAPI::fromJsonValue(calls_volume, json[QString("calls_volume")]); + + + m_puts_volume_isValid = ::OpenAPI::fromJsonValue(puts_volume, json[QString("puts_volume")]); + + + m_currency_pair_isValid = ::OpenAPI::fromJsonValue(currency_pair, json[QString("currency_pair")]); + + + m_futures_volume_isValid = ::OpenAPI::fromJsonValue(futures_volume, json[QString("futures_volume")]); + + +} + +QString +OAITrades_volumes::asJson () const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject +OAITrades_volumes::asJsonObject() const { + QJsonObject obj; + if(m_calls_volume_isSet){ + obj.insert(QString("calls_volume"), ::OpenAPI::toJsonValue(calls_volume)); + } + if(m_puts_volume_isSet){ + obj.insert(QString("puts_volume"), ::OpenAPI::toJsonValue(puts_volume)); + } + if(m_currency_pair_isSet){ + obj.insert(QString("currency_pair"), ::OpenAPI::toJsonValue(currency_pair)); + } + if(m_futures_volume_isSet){ + obj.insert(QString("futures_volume"), ::OpenAPI::toJsonValue(futures_volume)); + } + return obj; +} + + +double +OAITrades_volumes::getCallsVolume() const { + return calls_volume; +} +void +OAITrades_volumes::setCallsVolume(const double &calls_volume) { + this->calls_volume = calls_volume; + this->m_calls_volume_isSet = true; +} + + +double +OAITrades_volumes::getPutsVolume() const { + return puts_volume; +} +void +OAITrades_volumes::setPutsVolume(const double &puts_volume) { + this->puts_volume = puts_volume; + this->m_puts_volume_isSet = true; +} + + +QString +OAITrades_volumes::getCurrencyPair() const { + return currency_pair; +} +void +OAITrades_volumes::setCurrencyPair(const QString ¤cy_pair) { + this->currency_pair = currency_pair; + this->m_currency_pair_isSet = true; +} + + +double +OAITrades_volumes::getFuturesVolume() const { + return futures_volume; +} +void +OAITrades_volumes::setFuturesVolume(const double &futures_volume) { + this->futures_volume = futures_volume; + this->m_futures_volume_isSet = true; +} + +bool +OAITrades_volumes::isSet() const { + bool isObjectUpdated = false; + do{ + if(m_calls_volume_isSet){ isObjectUpdated = true; break;} + + if(m_puts_volume_isSet){ isObjectUpdated = true; break;} + + if(m_currency_pair_isSet){ isObjectUpdated = true; break;} + + if(m_futures_volume_isSet){ isObjectUpdated = true; break;} + }while(false); + return isObjectUpdated; +} + +bool +OAITrades_volumes::isValid() const { + // only required properties are required for the object to be considered valid + return m_calls_volume_isValid && m_puts_volume_isValid && m_currency_pair_isValid && m_futures_volume_isValid && true; +} + +} + diff --git a/cpp-qt5-client/client/OAITrades_volumes.h b/cpp-qt5-client/client/OAITrades_volumes.h new file mode 100644 index 0000000..a4b26f4 --- /dev/null +++ b/cpp-qt5-client/client/OAITrades_volumes.h @@ -0,0 +1,87 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OAITrades_volumes.h + * + * + */ + +#ifndef OAITrades_volumes_H +#define OAITrades_volumes_H + +#include + + +#include + +#include "OAIObject.h" +#include "OAIEnum.h" + +namespace OpenAPI { + +class OAITrades_volumes: public OAIObject { +public: + OAITrades_volumes(); + OAITrades_volumes(QString json); + ~OAITrades_volumes() override; + + QString asJson () const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + + double getCallsVolume() const; + void setCallsVolume(const double &calls_volume); + + + double getPutsVolume() const; + void setPutsVolume(const double &puts_volume); + + + QString getCurrencyPair() const; + void setCurrencyPair(const QString ¤cy_pair); + + + double getFuturesVolume() const; + void setFuturesVolume(const double &futures_volume); + + + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void init(); + + double calls_volume; + bool m_calls_volume_isSet; + bool m_calls_volume_isValid; + + double puts_volume; + bool m_puts_volume_isSet; + bool m_puts_volume_isValid; + + QString currency_pair; + bool m_currency_pair_isSet; + bool m_currency_pair_isValid; + + double futures_volume; + bool m_futures_volume_isSet; + bool m_futures_volume_isValid; + + }; + +} + +#endif // OAITrades_volumes_H diff --git a/cpp-qt5-client/client/OAITradingApi.cpp b/cpp-qt5-client/client/OAITradingApi.cpp new file mode 100644 index 0000000..3878e86 --- /dev/null +++ b/cpp-qt5-client/client/OAITradingApi.cpp @@ -0,0 +1,1823 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "OAITradingApi.h" +#include "OAIHelpers.h" + +#include +#include + +namespace OpenAPI { + +OAITradingApi::OAITradingApi() : basePath("/api/v2"), + host("www.deribit.com") { + +} + +OAITradingApi::~OAITradingApi() { + +} + +OAITradingApi::OAITradingApi(const QString& host, const QString& basePath) { + this->host = host; + this->basePath = basePath; +} + +void OAITradingApi::setBasePath(const QString& basePath){ + this->basePath = basePath; +} + +void OAITradingApi::setHost(const QString& host){ + this->host = host; +} + +void OAITradingApi::addHeaders(const QString& key, const QString& value){ + defaultHeaders.insert(key, value); +} + + +void +OAITradingApi::privateBuyGet(const QString& instrument_name, const double& amount, const QString& type, const QString& label, const double& price, const QString& time_in_force, const double& max_show, const bool& post_only, const bool& reduce_only, const double& stop_price, const QString& trigger, const QString& advanced) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/buy"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("amount")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(amount))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("label")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(label))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("price")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(price))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("time_in_force")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(time_in_force))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("max_show")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(max_show))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("post_only")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(post_only))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("reduce_only")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(reduce_only))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("stop_price")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(stop_price))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("trigger")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(trigger))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("advanced")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(advanced))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAITradingApi::privateBuyGetCallback); + + worker->execute(&input); +} + +void +OAITradingApi::privateBuyGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateBuyGetSignal(output); + emit privateBuyGetSignalFull(worker, output); + } else { + emit privateBuyGetSignalE(output, error_type, error_str); + emit privateBuyGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAITradingApi::privateCancelAllByCurrencyGet(const QString& currency, const QString& kind, const QString& type) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/cancel_all_by_currency"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("kind")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(kind))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAITradingApi::privateCancelAllByCurrencyGetCallback); + + worker->execute(&input); +} + +void +OAITradingApi::privateCancelAllByCurrencyGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateCancelAllByCurrencyGetSignal(output); + emit privateCancelAllByCurrencyGetSignalFull(worker, output); + } else { + emit privateCancelAllByCurrencyGetSignalE(output, error_type, error_str); + emit privateCancelAllByCurrencyGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAITradingApi::privateCancelAllByInstrumentGet(const QString& instrument_name, const QString& type) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/cancel_all_by_instrument"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAITradingApi::privateCancelAllByInstrumentGetCallback); + + worker->execute(&input); +} + +void +OAITradingApi::privateCancelAllByInstrumentGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateCancelAllByInstrumentGetSignal(output); + emit privateCancelAllByInstrumentGetSignalFull(worker, output); + } else { + emit privateCancelAllByInstrumentGetSignalE(output, error_type, error_str); + emit privateCancelAllByInstrumentGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAITradingApi::privateCancelAllGet() { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/cancel_all"); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAITradingApi::privateCancelAllGetCallback); + + worker->execute(&input); +} + +void +OAITradingApi::privateCancelAllGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateCancelAllGetSignal(output); + emit privateCancelAllGetSignalFull(worker, output); + } else { + emit privateCancelAllGetSignalE(output, error_type, error_str); + emit privateCancelAllGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAITradingApi::privateCancelGet(const QString& order_id) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/cancel"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("order_id")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(order_id))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAITradingApi::privateCancelGetCallback); + + worker->execute(&input); +} + +void +OAITradingApi::privateCancelGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateCancelGetSignal(output); + emit privateCancelGetSignalFull(worker, output); + } else { + emit privateCancelGetSignalE(output, error_type, error_str); + emit privateCancelGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAITradingApi::privateClosePositionGet(const QString& instrument_name, const QString& type, const double& price) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/close_position"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("price")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(price))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAITradingApi::privateClosePositionGetCallback); + + worker->execute(&input); +} + +void +OAITradingApi::privateClosePositionGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateClosePositionGetSignal(output); + emit privateClosePositionGetSignalFull(worker, output); + } else { + emit privateClosePositionGetSignalE(output, error_type, error_str); + emit privateClosePositionGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAITradingApi::privateEditGet(const QString& order_id, const double& amount, const double& price, const bool& post_only, const QString& advanced, const double& stop_price) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/edit"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("order_id")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(order_id))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("amount")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(amount))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("price")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(price))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("post_only")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(post_only))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("advanced")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(advanced))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("stop_price")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(stop_price))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAITradingApi::privateEditGetCallback); + + worker->execute(&input); +} + +void +OAITradingApi::privateEditGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateEditGetSignal(output); + emit privateEditGetSignalFull(worker, output); + } else { + emit privateEditGetSignalE(output, error_type, error_str); + emit privateEditGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAITradingApi::privateGetMarginsGet(const QString& instrument_name, const double& amount, const double& price) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_margins"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("amount")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(amount))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("price")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(price))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAITradingApi::privateGetMarginsGetCallback); + + worker->execute(&input); +} + +void +OAITradingApi::privateGetMarginsGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetMarginsGetSignal(output); + emit privateGetMarginsGetSignalFull(worker, output); + } else { + emit privateGetMarginsGetSignalE(output, error_type, error_str); + emit privateGetMarginsGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAITradingApi::privateGetOpenOrdersByCurrencyGet(const QString& currency, const QString& kind, const QString& type) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_open_orders_by_currency"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("kind")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(kind))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAITradingApi::privateGetOpenOrdersByCurrencyGetCallback); + + worker->execute(&input); +} + +void +OAITradingApi::privateGetOpenOrdersByCurrencyGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetOpenOrdersByCurrencyGetSignal(output); + emit privateGetOpenOrdersByCurrencyGetSignalFull(worker, output); + } else { + emit privateGetOpenOrdersByCurrencyGetSignalE(output, error_type, error_str); + emit privateGetOpenOrdersByCurrencyGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAITradingApi::privateGetOpenOrdersByInstrumentGet(const QString& instrument_name, const QString& type) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_open_orders_by_instrument"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAITradingApi::privateGetOpenOrdersByInstrumentGetCallback); + + worker->execute(&input); +} + +void +OAITradingApi::privateGetOpenOrdersByInstrumentGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetOpenOrdersByInstrumentGetSignal(output); + emit privateGetOpenOrdersByInstrumentGetSignalFull(worker, output); + } else { + emit privateGetOpenOrdersByInstrumentGetSignalE(output, error_type, error_str); + emit privateGetOpenOrdersByInstrumentGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAITradingApi::privateGetOrderHistoryByCurrencyGet(const QString& currency, const QString& kind, const qint32& count, const qint32& offset, const bool& include_old, const bool& include_unfilled) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_order_history_by_currency"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("kind")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(kind))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("offset")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(offset))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("include_old")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(include_old))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("include_unfilled")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(include_unfilled))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAITradingApi::privateGetOrderHistoryByCurrencyGetCallback); + + worker->execute(&input); +} + +void +OAITradingApi::privateGetOrderHistoryByCurrencyGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetOrderHistoryByCurrencyGetSignal(output); + emit privateGetOrderHistoryByCurrencyGetSignalFull(worker, output); + } else { + emit privateGetOrderHistoryByCurrencyGetSignalE(output, error_type, error_str); + emit privateGetOrderHistoryByCurrencyGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAITradingApi::privateGetOrderHistoryByInstrumentGet(const QString& instrument_name, const qint32& count, const qint32& offset, const bool& include_old, const bool& include_unfilled) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_order_history_by_instrument"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("offset")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(offset))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("include_old")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(include_old))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("include_unfilled")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(include_unfilled))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAITradingApi::privateGetOrderHistoryByInstrumentGetCallback); + + worker->execute(&input); +} + +void +OAITradingApi::privateGetOrderHistoryByInstrumentGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetOrderHistoryByInstrumentGetSignal(output); + emit privateGetOrderHistoryByInstrumentGetSignalFull(worker, output); + } else { + emit privateGetOrderHistoryByInstrumentGetSignalE(output, error_type, error_str); + emit privateGetOrderHistoryByInstrumentGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAITradingApi::privateGetOrderMarginByIdsGet(const QList& ids) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_order_margin_by_ids"); + + if (ids.size() > 0) { + if (QString("multi").indexOf("multi") == 0) { + foreach(QString t, ids) { + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append("ids=").append(::OpenAPI::toStringValue(t)); + } + } + else if (QString("multi").indexOf("ssv") == 0) { + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append("ids="); + qint32 count = 0; + foreach(QString t, ids) { + if (count > 0) { + fullPath.append(" "); + } + fullPath.append(::OpenAPI::toStringValue(t)); + } + } + else if (QString("multi").indexOf("tsv") == 0) { + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append("ids="); + qint32 count = 0; + foreach(QString t, ids) { + if (count > 0) { + fullPath.append("\t"); + } + fullPath.append(::OpenAPI::toStringValue(t)); + } + } + } + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAITradingApi::privateGetOrderMarginByIdsGetCallback); + + worker->execute(&input); +} + +void +OAITradingApi::privateGetOrderMarginByIdsGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetOrderMarginByIdsGetSignal(output); + emit privateGetOrderMarginByIdsGetSignalFull(worker, output); + } else { + emit privateGetOrderMarginByIdsGetSignalE(output, error_type, error_str); + emit privateGetOrderMarginByIdsGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAITradingApi::privateGetOrderStateGet(const QString& order_id) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_order_state"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("order_id")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(order_id))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAITradingApi::privateGetOrderStateGetCallback); + + worker->execute(&input); +} + +void +OAITradingApi::privateGetOrderStateGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetOrderStateGetSignal(output); + emit privateGetOrderStateGetSignalFull(worker, output); + } else { + emit privateGetOrderStateGetSignalE(output, error_type, error_str); + emit privateGetOrderStateGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAITradingApi::privateGetSettlementHistoryByCurrencyGet(const QString& currency, const QString& type, const qint32& count) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_settlement_history_by_currency"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAITradingApi::privateGetSettlementHistoryByCurrencyGetCallback); + + worker->execute(&input); +} + +void +OAITradingApi::privateGetSettlementHistoryByCurrencyGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetSettlementHistoryByCurrencyGetSignal(output); + emit privateGetSettlementHistoryByCurrencyGetSignalFull(worker, output); + } else { + emit privateGetSettlementHistoryByCurrencyGetSignalE(output, error_type, error_str); + emit privateGetSettlementHistoryByCurrencyGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAITradingApi::privateGetSettlementHistoryByInstrumentGet(const QString& instrument_name, const QString& type, const qint32& count) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_settlement_history_by_instrument"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAITradingApi::privateGetSettlementHistoryByInstrumentGetCallback); + + worker->execute(&input); +} + +void +OAITradingApi::privateGetSettlementHistoryByInstrumentGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetSettlementHistoryByInstrumentGetSignal(output); + emit privateGetSettlementHistoryByInstrumentGetSignalFull(worker, output); + } else { + emit privateGetSettlementHistoryByInstrumentGetSignalE(output, error_type, error_str); + emit privateGetSettlementHistoryByInstrumentGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAITradingApi::privateGetUserTradesByCurrencyAndTimeGet(const QString& currency, const qint32& start_timestamp, const qint32& end_timestamp, const QString& kind, const qint32& count, const bool& include_old, const QString& sorting) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_user_trades_by_currency_and_time"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("kind")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(kind))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("start_timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(start_timestamp))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("end_timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(end_timestamp))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("include_old")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(include_old))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sorting")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sorting))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAITradingApi::privateGetUserTradesByCurrencyAndTimeGetCallback); + + worker->execute(&input); +} + +void +OAITradingApi::privateGetUserTradesByCurrencyAndTimeGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetUserTradesByCurrencyAndTimeGetSignal(output); + emit privateGetUserTradesByCurrencyAndTimeGetSignalFull(worker, output); + } else { + emit privateGetUserTradesByCurrencyAndTimeGetSignalE(output, error_type, error_str); + emit privateGetUserTradesByCurrencyAndTimeGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAITradingApi::privateGetUserTradesByCurrencyGet(const QString& currency, const QString& kind, const QString& start_id, const QString& end_id, const qint32& count, const bool& include_old, const QString& sorting) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_user_trades_by_currency"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("kind")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(kind))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("start_id")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(start_id))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("end_id")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(end_id))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("include_old")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(include_old))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sorting")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sorting))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAITradingApi::privateGetUserTradesByCurrencyGetCallback); + + worker->execute(&input); +} + +void +OAITradingApi::privateGetUserTradesByCurrencyGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetUserTradesByCurrencyGetSignal(output); + emit privateGetUserTradesByCurrencyGetSignalFull(worker, output); + } else { + emit privateGetUserTradesByCurrencyGetSignalE(output, error_type, error_str); + emit privateGetUserTradesByCurrencyGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAITradingApi::privateGetUserTradesByInstrumentAndTimeGet(const QString& instrument_name, const qint32& start_timestamp, const qint32& end_timestamp, const qint32& count, const bool& include_old, const QString& sorting) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_user_trades_by_instrument_and_time"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("start_timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(start_timestamp))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("end_timestamp")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(end_timestamp))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("include_old")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(include_old))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sorting")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sorting))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAITradingApi::privateGetUserTradesByInstrumentAndTimeGetCallback); + + worker->execute(&input); +} + +void +OAITradingApi::privateGetUserTradesByInstrumentAndTimeGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetUserTradesByInstrumentAndTimeGetSignal(output); + emit privateGetUserTradesByInstrumentAndTimeGetSignalFull(worker, output); + } else { + emit privateGetUserTradesByInstrumentAndTimeGetSignalE(output, error_type, error_str); + emit privateGetUserTradesByInstrumentAndTimeGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAITradingApi::privateGetUserTradesByInstrumentGet(const QString& instrument_name, const qint32& start_seq, const qint32& end_seq, const qint32& count, const bool& include_old, const QString& sorting) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_user_trades_by_instrument"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("start_seq")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(start_seq))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("end_seq")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(end_seq))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("include_old")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(include_old))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sorting")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sorting))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAITradingApi::privateGetUserTradesByInstrumentGetCallback); + + worker->execute(&input); +} + +void +OAITradingApi::privateGetUserTradesByInstrumentGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetUserTradesByInstrumentGetSignal(output); + emit privateGetUserTradesByInstrumentGetSignalFull(worker, output); + } else { + emit privateGetUserTradesByInstrumentGetSignalE(output, error_type, error_str); + emit privateGetUserTradesByInstrumentGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAITradingApi::privateGetUserTradesByOrderGet(const QString& order_id, const QString& sorting) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_user_trades_by_order"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("order_id")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(order_id))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("sorting")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(sorting))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAITradingApi::privateGetUserTradesByOrderGetCallback); + + worker->execute(&input); +} + +void +OAITradingApi::privateGetUserTradesByOrderGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetUserTradesByOrderGetSignal(output); + emit privateGetUserTradesByOrderGetSignalFull(worker, output); + } else { + emit privateGetUserTradesByOrderGetSignalE(output, error_type, error_str); + emit privateGetUserTradesByOrderGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAITradingApi::privateSellGet(const QString& instrument_name, const double& amount, const QString& type, const QString& label, const double& price, const QString& time_in_force, const double& max_show, const bool& post_only, const bool& reduce_only, const double& stop_price, const QString& trigger, const QString& advanced) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/sell"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("instrument_name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(instrument_name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("amount")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(amount))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("label")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(label))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("price")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(price))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("time_in_force")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(time_in_force))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("max_show")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(max_show))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("post_only")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(post_only))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("reduce_only")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(reduce_only))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("stop_price")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(stop_price))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("trigger")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(trigger))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("advanced")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(advanced))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAITradingApi::privateSellGetCallback); + + worker->execute(&input); +} + +void +OAITradingApi::privateSellGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateSellGetSignal(output); + emit privateSellGetSignalFull(worker, output); + } else { + emit privateSellGetSignalE(output, error_type, error_str); + emit privateSellGetSignalEFull(worker, error_type, error_str); + } +} + + +} diff --git a/cpp-qt5-client/client/OAITradingApi.h b/cpp-qt5-client/client/OAITradingApi.h new file mode 100644 index 0000000..e24104c --- /dev/null +++ b/cpp-qt5-client/client/OAITradingApi.h @@ -0,0 +1,183 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#ifndef OAI_OAITradingApi_H +#define OAI_OAITradingApi_H + +#include "OAIHttpRequest.h" + +#include "OAIObject.h" +#include + +#include + +namespace OpenAPI { + +class OAITradingApi: public QObject { + Q_OBJECT + +public: + OAITradingApi(); + OAITradingApi(const QString& host, const QString& basePath); + ~OAITradingApi(); + + void setBasePath(const QString& basePath); + void setHost(const QString& host); + void addHeaders(const QString& key, const QString& value); + + void privateBuyGet(const QString& instrument_name, const double& amount, const QString& type, const QString& label, const double& price, const QString& time_in_force, const double& max_show, const bool& post_only, const bool& reduce_only, const double& stop_price, const QString& trigger, const QString& advanced); + void privateCancelAllByCurrencyGet(const QString& currency, const QString& kind, const QString& type); + void privateCancelAllByInstrumentGet(const QString& instrument_name, const QString& type); + void privateCancelAllGet(); + void privateCancelGet(const QString& order_id); + void privateClosePositionGet(const QString& instrument_name, const QString& type, const double& price); + void privateEditGet(const QString& order_id, const double& amount, const double& price, const bool& post_only, const QString& advanced, const double& stop_price); + void privateGetMarginsGet(const QString& instrument_name, const double& amount, const double& price); + void privateGetOpenOrdersByCurrencyGet(const QString& currency, const QString& kind, const QString& type); + void privateGetOpenOrdersByInstrumentGet(const QString& instrument_name, const QString& type); + void privateGetOrderHistoryByCurrencyGet(const QString& currency, const QString& kind, const qint32& count, const qint32& offset, const bool& include_old, const bool& include_unfilled); + void privateGetOrderHistoryByInstrumentGet(const QString& instrument_name, const qint32& count, const qint32& offset, const bool& include_old, const bool& include_unfilled); + void privateGetOrderMarginByIdsGet(const QList& ids); + void privateGetOrderStateGet(const QString& order_id); + void privateGetSettlementHistoryByCurrencyGet(const QString& currency, const QString& type, const qint32& count); + void privateGetSettlementHistoryByInstrumentGet(const QString& instrument_name, const QString& type, const qint32& count); + void privateGetUserTradesByCurrencyAndTimeGet(const QString& currency, const qint32& start_timestamp, const qint32& end_timestamp, const QString& kind, const qint32& count, const bool& include_old, const QString& sorting); + void privateGetUserTradesByCurrencyGet(const QString& currency, const QString& kind, const QString& start_id, const QString& end_id, const qint32& count, const bool& include_old, const QString& sorting); + void privateGetUserTradesByInstrumentAndTimeGet(const QString& instrument_name, const qint32& start_timestamp, const qint32& end_timestamp, const qint32& count, const bool& include_old, const QString& sorting); + void privateGetUserTradesByInstrumentGet(const QString& instrument_name, const qint32& start_seq, const qint32& end_seq, const qint32& count, const bool& include_old, const QString& sorting); + void privateGetUserTradesByOrderGet(const QString& order_id, const QString& sorting); + void privateSellGet(const QString& instrument_name, const double& amount, const QString& type, const QString& label, const double& price, const QString& time_in_force, const double& max_show, const bool& post_only, const bool& reduce_only, const double& stop_price, const QString& trigger, const QString& advanced); + +private: + QString basePath; + QString host; + QMap defaultHeaders; + void privateBuyGetCallback (OAIHttpRequestWorker * worker); + void privateCancelAllByCurrencyGetCallback (OAIHttpRequestWorker * worker); + void privateCancelAllByInstrumentGetCallback (OAIHttpRequestWorker * worker); + void privateCancelAllGetCallback (OAIHttpRequestWorker * worker); + void privateCancelGetCallback (OAIHttpRequestWorker * worker); + void privateClosePositionGetCallback (OAIHttpRequestWorker * worker); + void privateEditGetCallback (OAIHttpRequestWorker * worker); + void privateGetMarginsGetCallback (OAIHttpRequestWorker * worker); + void privateGetOpenOrdersByCurrencyGetCallback (OAIHttpRequestWorker * worker); + void privateGetOpenOrdersByInstrumentGetCallback (OAIHttpRequestWorker * worker); + void privateGetOrderHistoryByCurrencyGetCallback (OAIHttpRequestWorker * worker); + void privateGetOrderHistoryByInstrumentGetCallback (OAIHttpRequestWorker * worker); + void privateGetOrderMarginByIdsGetCallback (OAIHttpRequestWorker * worker); + void privateGetOrderStateGetCallback (OAIHttpRequestWorker * worker); + void privateGetSettlementHistoryByCurrencyGetCallback (OAIHttpRequestWorker * worker); + void privateGetSettlementHistoryByInstrumentGetCallback (OAIHttpRequestWorker * worker); + void privateGetUserTradesByCurrencyAndTimeGetCallback (OAIHttpRequestWorker * worker); + void privateGetUserTradesByCurrencyGetCallback (OAIHttpRequestWorker * worker); + void privateGetUserTradesByInstrumentAndTimeGetCallback (OAIHttpRequestWorker * worker); + void privateGetUserTradesByInstrumentGetCallback (OAIHttpRequestWorker * worker); + void privateGetUserTradesByOrderGetCallback (OAIHttpRequestWorker * worker); + void privateSellGetCallback (OAIHttpRequestWorker * worker); + +signals: + void privateBuyGetSignal(OAIObject summary); + void privateCancelAllByCurrencyGetSignal(OAIObject summary); + void privateCancelAllByInstrumentGetSignal(OAIObject summary); + void privateCancelAllGetSignal(OAIObject summary); + void privateCancelGetSignal(OAIObject summary); + void privateClosePositionGetSignal(OAIObject summary); + void privateEditGetSignal(OAIObject summary); + void privateGetMarginsGetSignal(OAIObject summary); + void privateGetOpenOrdersByCurrencyGetSignal(OAIObject summary); + void privateGetOpenOrdersByInstrumentGetSignal(OAIObject summary); + void privateGetOrderHistoryByCurrencyGetSignal(OAIObject summary); + void privateGetOrderHistoryByInstrumentGetSignal(OAIObject summary); + void privateGetOrderMarginByIdsGetSignal(OAIObject summary); + void privateGetOrderStateGetSignal(OAIObject summary); + void privateGetSettlementHistoryByCurrencyGetSignal(OAIObject summary); + void privateGetSettlementHistoryByInstrumentGetSignal(OAIObject summary); + void privateGetUserTradesByCurrencyAndTimeGetSignal(OAIObject summary); + void privateGetUserTradesByCurrencyGetSignal(OAIObject summary); + void privateGetUserTradesByInstrumentAndTimeGetSignal(OAIObject summary); + void privateGetUserTradesByInstrumentGetSignal(OAIObject summary); + void privateGetUserTradesByOrderGetSignal(OAIObject summary); + void privateSellGetSignal(OAIObject summary); + + void privateBuyGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateCancelAllByCurrencyGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateCancelAllByInstrumentGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateCancelAllGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateCancelGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateClosePositionGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateEditGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetMarginsGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetOpenOrdersByCurrencyGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetOpenOrdersByInstrumentGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetOrderHistoryByCurrencyGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetOrderHistoryByInstrumentGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetOrderMarginByIdsGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetOrderStateGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetSettlementHistoryByCurrencyGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetSettlementHistoryByInstrumentGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetUserTradesByCurrencyAndTimeGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetUserTradesByCurrencyGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetUserTradesByInstrumentAndTimeGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetUserTradesByInstrumentGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetUserTradesByOrderGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateSellGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + + void privateBuyGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCancelAllByCurrencyGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCancelAllByInstrumentGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCancelAllGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCancelGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateClosePositionGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateEditGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetMarginsGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetOpenOrdersByCurrencyGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetOpenOrdersByInstrumentGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetOrderHistoryByCurrencyGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetOrderHistoryByInstrumentGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetOrderMarginByIdsGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetOrderStateGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetSettlementHistoryByCurrencyGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetSettlementHistoryByInstrumentGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetUserTradesByCurrencyAndTimeGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetUserTradesByCurrencyGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetUserTradesByInstrumentAndTimeGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetUserTradesByInstrumentGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetUserTradesByOrderGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSellGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + + void privateBuyGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCancelAllByCurrencyGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCancelAllByInstrumentGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCancelAllGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCancelGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateClosePositionGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateEditGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetMarginsGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetOpenOrdersByCurrencyGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetOpenOrdersByInstrumentGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetOrderHistoryByCurrencyGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetOrderHistoryByInstrumentGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetOrderMarginByIdsGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetOrderStateGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetSettlementHistoryByCurrencyGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetSettlementHistoryByInstrumentGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetUserTradesByCurrencyAndTimeGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetUserTradesByCurrencyGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetUserTradesByInstrumentAndTimeGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetUserTradesByInstrumentGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetUserTradesByOrderGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSellGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + +}; + +} +#endif diff --git a/cpp-qt5-client/client/OAITransfer_item.cpp b/cpp-qt5-client/client/OAITransfer_item.cpp new file mode 100644 index 0000000..d4608ae --- /dev/null +++ b/cpp-qt5-client/client/OAITransfer_item.cpp @@ -0,0 +1,281 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include "OAITransfer_item.h" + +#include "OAIHelpers.h" + +#include +#include +#include +#include + +namespace OpenAPI { + +OAITransfer_item::OAITransfer_item(QString json) { + this->init(); + this->fromJson(json); +} + +OAITransfer_item::OAITransfer_item() { + this->init(); +} + +OAITransfer_item::~OAITransfer_item() { + +} + +void +OAITransfer_item::init() { + + m_updated_timestamp_isSet = false; + m_updated_timestamp_isValid = false; + + m_direction_isSet = false; + m_direction_isValid = false; + + m_amount_isSet = false; + m_amount_isValid = false; + + m_other_side_isSet = false; + m_other_side_isValid = false; + + m_currency_isSet = false; + m_currency_isValid = false; + + m_state_isSet = false; + m_state_isValid = false; + + m_created_timestamp_isSet = false; + m_created_timestamp_isValid = false; + + m_type_isSet = false; + m_type_isValid = false; + + m_id_isSet = false; + m_id_isValid = false; + } + +void +OAITransfer_item::fromJson(QString jsonString) { + QByteArray array (jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void +OAITransfer_item::fromJsonObject(QJsonObject json) { + + m_updated_timestamp_isValid = ::OpenAPI::fromJsonValue(updated_timestamp, json[QString("updated_timestamp")]); + + + m_direction_isValid = ::OpenAPI::fromJsonValue(direction, json[QString("direction")]); + + + m_amount_isValid = ::OpenAPI::fromJsonValue(amount, json[QString("amount")]); + + + m_other_side_isValid = ::OpenAPI::fromJsonValue(other_side, json[QString("other_side")]); + + + m_currency_isValid = ::OpenAPI::fromJsonValue(currency, json[QString("currency")]); + + + m_state_isValid = ::OpenAPI::fromJsonValue(state, json[QString("state")]); + + + m_created_timestamp_isValid = ::OpenAPI::fromJsonValue(created_timestamp, json[QString("created_timestamp")]); + + + m_type_isValid = ::OpenAPI::fromJsonValue(type, json[QString("type")]); + + + m_id_isValid = ::OpenAPI::fromJsonValue(id, json[QString("id")]); + + +} + +QString +OAITransfer_item::asJson () const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject +OAITransfer_item::asJsonObject() const { + QJsonObject obj; + if(m_updated_timestamp_isSet){ + obj.insert(QString("updated_timestamp"), ::OpenAPI::toJsonValue(updated_timestamp)); + } + if(m_direction_isSet){ + obj.insert(QString("direction"), ::OpenAPI::toJsonValue(direction)); + } + if(m_amount_isSet){ + obj.insert(QString("amount"), ::OpenAPI::toJsonValue(amount)); + } + if(m_other_side_isSet){ + obj.insert(QString("other_side"), ::OpenAPI::toJsonValue(other_side)); + } + if(m_currency_isSet){ + obj.insert(QString("currency"), ::OpenAPI::toJsonValue(currency)); + } + if(m_state_isSet){ + obj.insert(QString("state"), ::OpenAPI::toJsonValue(state)); + } + if(m_created_timestamp_isSet){ + obj.insert(QString("created_timestamp"), ::OpenAPI::toJsonValue(created_timestamp)); + } + if(m_type_isSet){ + obj.insert(QString("type"), ::OpenAPI::toJsonValue(type)); + } + if(m_id_isSet){ + obj.insert(QString("id"), ::OpenAPI::toJsonValue(id)); + } + return obj; +} + + +qint32 +OAITransfer_item::getUpdatedTimestamp() const { + return updated_timestamp; +} +void +OAITransfer_item::setUpdatedTimestamp(const qint32 &updated_timestamp) { + this->updated_timestamp = updated_timestamp; + this->m_updated_timestamp_isSet = true; +} + + +QString +OAITransfer_item::getDirection() const { + return direction; +} +void +OAITransfer_item::setDirection(const QString &direction) { + this->direction = direction; + this->m_direction_isSet = true; +} + + +double +OAITransfer_item::getAmount() const { + return amount; +} +void +OAITransfer_item::setAmount(const double &amount) { + this->amount = amount; + this->m_amount_isSet = true; +} + + +QString +OAITransfer_item::getOtherSide() const { + return other_side; +} +void +OAITransfer_item::setOtherSide(const QString &other_side) { + this->other_side = other_side; + this->m_other_side_isSet = true; +} + + +QString +OAITransfer_item::getCurrency() const { + return currency; +} +void +OAITransfer_item::setCurrency(const QString ¤cy) { + this->currency = currency; + this->m_currency_isSet = true; +} + + +QString +OAITransfer_item::getState() const { + return state; +} +void +OAITransfer_item::setState(const QString &state) { + this->state = state; + this->m_state_isSet = true; +} + + +qint32 +OAITransfer_item::getCreatedTimestamp() const { + return created_timestamp; +} +void +OAITransfer_item::setCreatedTimestamp(const qint32 &created_timestamp) { + this->created_timestamp = created_timestamp; + this->m_created_timestamp_isSet = true; +} + + +QString +OAITransfer_item::getType() const { + return type; +} +void +OAITransfer_item::setType(const QString &type) { + this->type = type; + this->m_type_isSet = true; +} + + +qint32 +OAITransfer_item::getId() const { + return id; +} +void +OAITransfer_item::setId(const qint32 &id) { + this->id = id; + this->m_id_isSet = true; +} + +bool +OAITransfer_item::isSet() const { + bool isObjectUpdated = false; + do{ + if(m_updated_timestamp_isSet){ isObjectUpdated = true; break;} + + if(m_direction_isSet){ isObjectUpdated = true; break;} + + if(m_amount_isSet){ isObjectUpdated = true; break;} + + if(m_other_side_isSet){ isObjectUpdated = true; break;} + + if(m_currency_isSet){ isObjectUpdated = true; break;} + + if(m_state_isSet){ isObjectUpdated = true; break;} + + if(m_created_timestamp_isSet){ isObjectUpdated = true; break;} + + if(m_type_isSet){ isObjectUpdated = true; break;} + + if(m_id_isSet){ isObjectUpdated = true; break;} + }while(false); + return isObjectUpdated; +} + +bool +OAITransfer_item::isValid() const { + // only required properties are required for the object to be considered valid + return m_updated_timestamp_isValid && m_amount_isValid && m_other_side_isValid && m_currency_isValid && m_state_isValid && m_created_timestamp_isValid && m_type_isValid && m_id_isValid && true; +} + +} + diff --git a/cpp-qt5-client/client/OAITransfer_item.h b/cpp-qt5-client/client/OAITransfer_item.h new file mode 100644 index 0000000..6c9b888 --- /dev/null +++ b/cpp-qt5-client/client/OAITransfer_item.h @@ -0,0 +1,127 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OAITransfer_item.h + * + * + */ + +#ifndef OAITransfer_item_H +#define OAITransfer_item_H + +#include + + +#include + +#include "OAIObject.h" +#include "OAIEnum.h" + +namespace OpenAPI { + +class OAITransfer_item: public OAIObject { +public: + OAITransfer_item(); + OAITransfer_item(QString json); + ~OAITransfer_item() override; + + QString asJson () const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + + qint32 getUpdatedTimestamp() const; + void setUpdatedTimestamp(const qint32 &updated_timestamp); + + + QString getDirection() const; + void setDirection(const QString &direction); + + + double getAmount() const; + void setAmount(const double &amount); + + + QString getOtherSide() const; + void setOtherSide(const QString &other_side); + + + QString getCurrency() const; + void setCurrency(const QString ¤cy); + + + QString getState() const; + void setState(const QString &state); + + + qint32 getCreatedTimestamp() const; + void setCreatedTimestamp(const qint32 &created_timestamp); + + + QString getType() const; + void setType(const QString &type); + + + qint32 getId() const; + void setId(const qint32 &id); + + + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void init(); + + qint32 updated_timestamp; + bool m_updated_timestamp_isSet; + bool m_updated_timestamp_isValid; + + QString direction; + bool m_direction_isSet; + bool m_direction_isValid; + + double amount; + bool m_amount_isSet; + bool m_amount_isValid; + + QString other_side; + bool m_other_side_isSet; + bool m_other_side_isValid; + + QString currency; + bool m_currency_isSet; + bool m_currency_isValid; + + QString state; + bool m_state_isSet; + bool m_state_isValid; + + qint32 created_timestamp; + bool m_created_timestamp_isSet; + bool m_created_timestamp_isValid; + + QString type; + bool m_type_isSet; + bool m_type_isValid; + + qint32 id; + bool m_id_isSet; + bool m_id_isValid; + + }; + +} + +#endif // OAITransfer_item_H diff --git a/cpp-qt5-client/client/OAITypes.cpp b/cpp-qt5-client/client/OAITypes.cpp new file mode 100644 index 0000000..fa21698 --- /dev/null +++ b/cpp-qt5-client/client/OAITypes.cpp @@ -0,0 +1,83 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include "OAITypes.h" + +#include "OAIHelpers.h" + +#include +#include +#include +#include + +namespace OpenAPI { + +OAITypes::OAITypes(QString json) { + this->init(); + this->fromJson(json); +} + +OAITypes::OAITypes() { + this->init(); +} + +OAITypes::~OAITypes() { + +} + +void +OAITypes::init() { + } + +void +OAITypes::fromJson(QString jsonString) { + QByteArray array (jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void +OAITypes::fromJsonObject(QJsonObject json) { + +} + +QString +OAITypes::asJson () const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject +OAITypes::asJsonObject() const { + QJsonObject obj; + return obj; +} + +bool +OAITypes::isSet() const { + bool isObjectUpdated = false; + do{ }while(false); + return isObjectUpdated; +} + +bool +OAITypes::isValid() const { + // only required properties are required for the object to be considered valid + return true; +} + +} + diff --git a/cpp-qt5-client/client/OAITypes.h b/cpp-qt5-client/client/OAITypes.h new file mode 100644 index 0000000..a894f4c --- /dev/null +++ b/cpp-qt5-client/client/OAITypes.h @@ -0,0 +1,54 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OAITypes.h + * + * + */ + +#ifndef OAITypes_H +#define OAITypes_H + +#include + + + +#include "OAIObject.h" +#include "OAIEnum.h" + +namespace OpenAPI { + +class OAITypes: public OAIObject { +public: + OAITypes(); + OAITypes(QString json); + ~OAITypes() override; + + QString asJson () const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void init(); + + }; + +} + +#endif // OAITypes_H diff --git a/cpp-qt5-client/client/OAIUser_trade.cpp b/cpp-qt5-client/client/OAIUser_trade.cpp new file mode 100644 index 0000000..ff54d33 --- /dev/null +++ b/cpp-qt5-client/client/OAIUser_trade.cpp @@ -0,0 +1,501 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include "OAIUser_trade.h" + +#include "OAIHelpers.h" + +#include +#include +#include +#include + +namespace OpenAPI { + +OAIUser_trade::OAIUser_trade(QString json) { + this->init(); + this->fromJson(json); +} + +OAIUser_trade::OAIUser_trade() { + this->init(); +} + +OAIUser_trade::~OAIUser_trade() { + +} + +void +OAIUser_trade::init() { + + m_direction_isSet = false; + m_direction_isValid = false; + + m_fee_currency_isSet = false; + m_fee_currency_isValid = false; + + m_order_id_isSet = false; + m_order_id_isValid = false; + + m_timestamp_isSet = false; + m_timestamp_isValid = false; + + m_price_isSet = false; + m_price_isValid = false; + + m_iv_isSet = false; + m_iv_isValid = false; + + m_trade_id_isSet = false; + m_trade_id_isValid = false; + + m_fee_isSet = false; + m_fee_isValid = false; + + m_order_type_isSet = false; + m_order_type_isValid = false; + + m_trade_seq_isSet = false; + m_trade_seq_isValid = false; + + m_self_trade_isSet = false; + m_self_trade_isValid = false; + + m_state_isSet = false; + m_state_isValid = false; + + m_label_isSet = false; + m_label_isValid = false; + + m_index_price_isSet = false; + m_index_price_isValid = false; + + m_amount_isSet = false; + m_amount_isValid = false; + + m_instrument_name_isSet = false; + m_instrument_name_isValid = false; + + m_tick_direction_isSet = false; + m_tick_direction_isValid = false; + + m_matching_id_isSet = false; + m_matching_id_isValid = false; + + m_liquidity_isSet = false; + m_liquidity_isValid = false; + } + +void +OAIUser_trade::fromJson(QString jsonString) { + QByteArray array (jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void +OAIUser_trade::fromJsonObject(QJsonObject json) { + + m_direction_isValid = ::OpenAPI::fromJsonValue(direction, json[QString("direction")]); + + + m_fee_currency_isValid = ::OpenAPI::fromJsonValue(fee_currency, json[QString("fee_currency")]); + + + m_order_id_isValid = ::OpenAPI::fromJsonValue(order_id, json[QString("order_id")]); + + + m_timestamp_isValid = ::OpenAPI::fromJsonValue(timestamp, json[QString("timestamp")]); + + + m_price_isValid = ::OpenAPI::fromJsonValue(price, json[QString("price")]); + + + m_iv_isValid = ::OpenAPI::fromJsonValue(iv, json[QString("iv")]); + + + m_trade_id_isValid = ::OpenAPI::fromJsonValue(trade_id, json[QString("trade_id")]); + + + m_fee_isValid = ::OpenAPI::fromJsonValue(fee, json[QString("fee")]); + + + m_order_type_isValid = ::OpenAPI::fromJsonValue(order_type, json[QString("order_type")]); + + + m_trade_seq_isValid = ::OpenAPI::fromJsonValue(trade_seq, json[QString("trade_seq")]); + + + m_self_trade_isValid = ::OpenAPI::fromJsonValue(self_trade, json[QString("self_trade")]); + + + m_state_isValid = ::OpenAPI::fromJsonValue(state, json[QString("state")]); + + + m_label_isValid = ::OpenAPI::fromJsonValue(label, json[QString("label")]); + + + m_index_price_isValid = ::OpenAPI::fromJsonValue(index_price, json[QString("index_price")]); + + + m_amount_isValid = ::OpenAPI::fromJsonValue(amount, json[QString("amount")]); + + + m_instrument_name_isValid = ::OpenAPI::fromJsonValue(instrument_name, json[QString("instrument_name")]); + + + m_tick_direction_isValid = ::OpenAPI::fromJsonValue(tick_direction, json[QString("tick_direction")]); + + + m_matching_id_isValid = ::OpenAPI::fromJsonValue(matching_id, json[QString("matching_id")]); + + + m_liquidity_isValid = ::OpenAPI::fromJsonValue(liquidity, json[QString("liquidity")]); + + +} + +QString +OAIUser_trade::asJson () const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject +OAIUser_trade::asJsonObject() const { + QJsonObject obj; + if(m_direction_isSet){ + obj.insert(QString("direction"), ::OpenAPI::toJsonValue(direction)); + } + if(m_fee_currency_isSet){ + obj.insert(QString("fee_currency"), ::OpenAPI::toJsonValue(fee_currency)); + } + if(m_order_id_isSet){ + obj.insert(QString("order_id"), ::OpenAPI::toJsonValue(order_id)); + } + if(m_timestamp_isSet){ + obj.insert(QString("timestamp"), ::OpenAPI::toJsonValue(timestamp)); + } + if(m_price_isSet){ + obj.insert(QString("price"), ::OpenAPI::toJsonValue(price)); + } + if(m_iv_isSet){ + obj.insert(QString("iv"), ::OpenAPI::toJsonValue(iv)); + } + if(m_trade_id_isSet){ + obj.insert(QString("trade_id"), ::OpenAPI::toJsonValue(trade_id)); + } + if(m_fee_isSet){ + obj.insert(QString("fee"), ::OpenAPI::toJsonValue(fee)); + } + if(m_order_type_isSet){ + obj.insert(QString("order_type"), ::OpenAPI::toJsonValue(order_type)); + } + if(m_trade_seq_isSet){ + obj.insert(QString("trade_seq"), ::OpenAPI::toJsonValue(trade_seq)); + } + if(m_self_trade_isSet){ + obj.insert(QString("self_trade"), ::OpenAPI::toJsonValue(self_trade)); + } + if(m_state_isSet){ + obj.insert(QString("state"), ::OpenAPI::toJsonValue(state)); + } + if(m_label_isSet){ + obj.insert(QString("label"), ::OpenAPI::toJsonValue(label)); + } + if(m_index_price_isSet){ + obj.insert(QString("index_price"), ::OpenAPI::toJsonValue(index_price)); + } + if(m_amount_isSet){ + obj.insert(QString("amount"), ::OpenAPI::toJsonValue(amount)); + } + if(m_instrument_name_isSet){ + obj.insert(QString("instrument_name"), ::OpenAPI::toJsonValue(instrument_name)); + } + if(m_tick_direction_isSet){ + obj.insert(QString("tick_direction"), ::OpenAPI::toJsonValue(tick_direction)); + } + if(m_matching_id_isSet){ + obj.insert(QString("matching_id"), ::OpenAPI::toJsonValue(matching_id)); + } + if(m_liquidity_isSet){ + obj.insert(QString("liquidity"), ::OpenAPI::toJsonValue(liquidity)); + } + return obj; +} + + +QString +OAIUser_trade::getDirection() const { + return direction; +} +void +OAIUser_trade::setDirection(const QString &direction) { + this->direction = direction; + this->m_direction_isSet = true; +} + + +QString +OAIUser_trade::getFeeCurrency() const { + return fee_currency; +} +void +OAIUser_trade::setFeeCurrency(const QString &fee_currency) { + this->fee_currency = fee_currency; + this->m_fee_currency_isSet = true; +} + + +QString +OAIUser_trade::getOrderId() const { + return order_id; +} +void +OAIUser_trade::setOrderId(const QString &order_id) { + this->order_id = order_id; + this->m_order_id_isSet = true; +} + + +qint32 +OAIUser_trade::getTimestamp() const { + return timestamp; +} +void +OAIUser_trade::setTimestamp(const qint32 ×tamp) { + this->timestamp = timestamp; + this->m_timestamp_isSet = true; +} + + +double +OAIUser_trade::getPrice() const { + return price; +} +void +OAIUser_trade::setPrice(const double &price) { + this->price = price; + this->m_price_isSet = true; +} + + +double +OAIUser_trade::getIv() const { + return iv; +} +void +OAIUser_trade::setIv(const double &iv) { + this->iv = iv; + this->m_iv_isSet = true; +} + + +QString +OAIUser_trade::getTradeId() const { + return trade_id; +} +void +OAIUser_trade::setTradeId(const QString &trade_id) { + this->trade_id = trade_id; + this->m_trade_id_isSet = true; +} + + +double +OAIUser_trade::getFee() const { + return fee; +} +void +OAIUser_trade::setFee(const double &fee) { + this->fee = fee; + this->m_fee_isSet = true; +} + + +QString +OAIUser_trade::getOrderType() const { + return order_type; +} +void +OAIUser_trade::setOrderType(const QString &order_type) { + this->order_type = order_type; + this->m_order_type_isSet = true; +} + + +qint32 +OAIUser_trade::getTradeSeq() const { + return trade_seq; +} +void +OAIUser_trade::setTradeSeq(const qint32 &trade_seq) { + this->trade_seq = trade_seq; + this->m_trade_seq_isSet = true; +} + + +bool +OAIUser_trade::isSelfTrade() const { + return self_trade; +} +void +OAIUser_trade::setSelfTrade(const bool &self_trade) { + this->self_trade = self_trade; + this->m_self_trade_isSet = true; +} + + +QString +OAIUser_trade::getState() const { + return state; +} +void +OAIUser_trade::setState(const QString &state) { + this->state = state; + this->m_state_isSet = true; +} + + +QString +OAIUser_trade::getLabel() const { + return label; +} +void +OAIUser_trade::setLabel(const QString &label) { + this->label = label; + this->m_label_isSet = true; +} + + +double +OAIUser_trade::getIndexPrice() const { + return index_price; +} +void +OAIUser_trade::setIndexPrice(const double &index_price) { + this->index_price = index_price; + this->m_index_price_isSet = true; +} + + +double +OAIUser_trade::getAmount() const { + return amount; +} +void +OAIUser_trade::setAmount(const double &amount) { + this->amount = amount; + this->m_amount_isSet = true; +} + + +QString +OAIUser_trade::getInstrumentName() const { + return instrument_name; +} +void +OAIUser_trade::setInstrumentName(const QString &instrument_name) { + this->instrument_name = instrument_name; + this->m_instrument_name_isSet = true; +} + + +qint32 +OAIUser_trade::getTickDirection() const { + return tick_direction; +} +void +OAIUser_trade::setTickDirection(const qint32 &tick_direction) { + this->tick_direction = tick_direction; + this->m_tick_direction_isSet = true; +} + + +QString +OAIUser_trade::getMatchingId() const { + return matching_id; +} +void +OAIUser_trade::setMatchingId(const QString &matching_id) { + this->matching_id = matching_id; + this->m_matching_id_isSet = true; +} + + +QString +OAIUser_trade::getLiquidity() const { + return liquidity; +} +void +OAIUser_trade::setLiquidity(const QString &liquidity) { + this->liquidity = liquidity; + this->m_liquidity_isSet = true; +} + +bool +OAIUser_trade::isSet() const { + bool isObjectUpdated = false; + do{ + if(m_direction_isSet){ isObjectUpdated = true; break;} + + if(m_fee_currency_isSet){ isObjectUpdated = true; break;} + + if(m_order_id_isSet){ isObjectUpdated = true; break;} + + if(m_timestamp_isSet){ isObjectUpdated = true; break;} + + if(m_price_isSet){ isObjectUpdated = true; break;} + + if(m_iv_isSet){ isObjectUpdated = true; break;} + + if(m_trade_id_isSet){ isObjectUpdated = true; break;} + + if(m_fee_isSet){ isObjectUpdated = true; break;} + + if(m_order_type_isSet){ isObjectUpdated = true; break;} + + if(m_trade_seq_isSet){ isObjectUpdated = true; break;} + + if(m_self_trade_isSet){ isObjectUpdated = true; break;} + + if(m_state_isSet){ isObjectUpdated = true; break;} + + if(m_label_isSet){ isObjectUpdated = true; break;} + + if(m_index_price_isSet){ isObjectUpdated = true; break;} + + if(m_amount_isSet){ isObjectUpdated = true; break;} + + if(m_instrument_name_isSet){ isObjectUpdated = true; break;} + + if(m_tick_direction_isSet){ isObjectUpdated = true; break;} + + if(m_matching_id_isSet){ isObjectUpdated = true; break;} + + if(m_liquidity_isSet){ isObjectUpdated = true; break;} + }while(false); + return isObjectUpdated; +} + +bool +OAIUser_trade::isValid() const { + // only required properties are required for the object to be considered valid + return m_direction_isValid && m_fee_currency_isValid && m_order_id_isValid && m_timestamp_isValid && m_price_isValid && m_trade_id_isValid && m_fee_isValid && m_trade_seq_isValid && m_self_trade_isValid && m_state_isValid && m_index_price_isValid && m_amount_isValid && m_instrument_name_isValid && m_tick_direction_isValid && m_matching_id_isValid && true; +} + +} + diff --git a/cpp-qt5-client/client/OAIUser_trade.h b/cpp-qt5-client/client/OAIUser_trade.h new file mode 100644 index 0000000..3ffbbef --- /dev/null +++ b/cpp-qt5-client/client/OAIUser_trade.h @@ -0,0 +1,207 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OAIUser_trade.h + * + * + */ + +#ifndef OAIUser_trade_H +#define OAIUser_trade_H + +#include + + +#include + +#include "OAIObject.h" +#include "OAIEnum.h" + +namespace OpenAPI { + +class OAIUser_trade: public OAIObject { +public: + OAIUser_trade(); + OAIUser_trade(QString json); + ~OAIUser_trade() override; + + QString asJson () const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + + QString getDirection() const; + void setDirection(const QString &direction); + + + QString getFeeCurrency() const; + void setFeeCurrency(const QString &fee_currency); + + + QString getOrderId() const; + void setOrderId(const QString &order_id); + + + qint32 getTimestamp() const; + void setTimestamp(const qint32 ×tamp); + + + double getPrice() const; + void setPrice(const double &price); + + + double getIv() const; + void setIv(const double &iv); + + + QString getTradeId() const; + void setTradeId(const QString &trade_id); + + + double getFee() const; + void setFee(const double &fee); + + + QString getOrderType() const; + void setOrderType(const QString &order_type); + + + qint32 getTradeSeq() const; + void setTradeSeq(const qint32 &trade_seq); + + + bool isSelfTrade() const; + void setSelfTrade(const bool &self_trade); + + + QString getState() const; + void setState(const QString &state); + + + QString getLabel() const; + void setLabel(const QString &label); + + + double getIndexPrice() const; + void setIndexPrice(const double &index_price); + + + double getAmount() const; + void setAmount(const double &amount); + + + QString getInstrumentName() const; + void setInstrumentName(const QString &instrument_name); + + + qint32 getTickDirection() const; + void setTickDirection(const qint32 &tick_direction); + + + QString getMatchingId() const; + void setMatchingId(const QString &matching_id); + + + QString getLiquidity() const; + void setLiquidity(const QString &liquidity); + + + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void init(); + + QString direction; + bool m_direction_isSet; + bool m_direction_isValid; + + QString fee_currency; + bool m_fee_currency_isSet; + bool m_fee_currency_isValid; + + QString order_id; + bool m_order_id_isSet; + bool m_order_id_isValid; + + qint32 timestamp; + bool m_timestamp_isSet; + bool m_timestamp_isValid; + + double price; + bool m_price_isSet; + bool m_price_isValid; + + double iv; + bool m_iv_isSet; + bool m_iv_isValid; + + QString trade_id; + bool m_trade_id_isSet; + bool m_trade_id_isValid; + + double fee; + bool m_fee_isSet; + bool m_fee_isValid; + + QString order_type; + bool m_order_type_isSet; + bool m_order_type_isValid; + + qint32 trade_seq; + bool m_trade_seq_isSet; + bool m_trade_seq_isValid; + + bool self_trade; + bool m_self_trade_isSet; + bool m_self_trade_isValid; + + QString state; + bool m_state_isSet; + bool m_state_isValid; + + QString label; + bool m_label_isSet; + bool m_label_isValid; + + double index_price; + bool m_index_price_isSet; + bool m_index_price_isValid; + + double amount; + bool m_amount_isSet; + bool m_amount_isValid; + + QString instrument_name; + bool m_instrument_name_isSet; + bool m_instrument_name_isValid; + + qint32 tick_direction; + bool m_tick_direction_isSet; + bool m_tick_direction_isValid; + + QString matching_id; + bool m_matching_id_isSet; + bool m_matching_id_isValid; + + QString liquidity; + bool m_liquidity_isSet; + bool m_liquidity_isValid; + + }; + +} + +#endif // OAIUser_trade_H diff --git a/cpp-qt5-client/client/OAIWalletApi.cpp b/cpp-qt5-client/client/OAIWalletApi.cpp new file mode 100644 index 0000000..2818a6d --- /dev/null +++ b/cpp-qt5-client/client/OAIWalletApi.cpp @@ -0,0 +1,1007 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#include "OAIWalletApi.h" +#include "OAIHelpers.h" + +#include +#include + +namespace OpenAPI { + +OAIWalletApi::OAIWalletApi() : basePath("/api/v2"), + host("www.deribit.com") { + +} + +OAIWalletApi::~OAIWalletApi() { + +} + +OAIWalletApi::OAIWalletApi(const QString& host, const QString& basePath) { + this->host = host; + this->basePath = basePath; +} + +void OAIWalletApi::setBasePath(const QString& basePath){ + this->basePath = basePath; +} + +void OAIWalletApi::setHost(const QString& host){ + this->host = host; +} + +void OAIWalletApi::addHeaders(const QString& key, const QString& value){ + defaultHeaders.insert(key, value); +} + + +void +OAIWalletApi::privateAddToAddressBookGet(const QString& currency, const QString& type, const QString& address, const QString& name, const QString& tfa) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/add_to_address_book"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("address")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(address))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("name")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(name))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("tfa")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(tfa))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIWalletApi::privateAddToAddressBookGetCallback); + + worker->execute(&input); +} + +void +OAIWalletApi::privateAddToAddressBookGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateAddToAddressBookGetSignal(output); + emit privateAddToAddressBookGetSignalFull(worker, output); + } else { + emit privateAddToAddressBookGetSignalE(output, error_type, error_str); + emit privateAddToAddressBookGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIWalletApi::privateCancelTransferByIdGet(const QString& currency, const qint32& id, const QString& tfa) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/cancel_transfer_by_id"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("id")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(id))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("tfa")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(tfa))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIWalletApi::privateCancelTransferByIdGetCallback); + + worker->execute(&input); +} + +void +OAIWalletApi::privateCancelTransferByIdGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateCancelTransferByIdGetSignal(output); + emit privateCancelTransferByIdGetSignalFull(worker, output); + } else { + emit privateCancelTransferByIdGetSignalE(output, error_type, error_str); + emit privateCancelTransferByIdGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIWalletApi::privateCancelWithdrawalGet(const QString& currency, const double& id) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/cancel_withdrawal"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("id")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(id))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIWalletApi::privateCancelWithdrawalGetCallback); + + worker->execute(&input); +} + +void +OAIWalletApi::privateCancelWithdrawalGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateCancelWithdrawalGetSignal(output); + emit privateCancelWithdrawalGetSignalFull(worker, output); + } else { + emit privateCancelWithdrawalGetSignalE(output, error_type, error_str); + emit privateCancelWithdrawalGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIWalletApi::privateCreateDepositAddressGet(const QString& currency) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/create_deposit_address"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIWalletApi::privateCreateDepositAddressGetCallback); + + worker->execute(&input); +} + +void +OAIWalletApi::privateCreateDepositAddressGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateCreateDepositAddressGetSignal(output); + emit privateCreateDepositAddressGetSignalFull(worker, output); + } else { + emit privateCreateDepositAddressGetSignalE(output, error_type, error_str); + emit privateCreateDepositAddressGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIWalletApi::privateGetAddressBookGet(const QString& currency, const QString& type) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_address_book"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIWalletApi::privateGetAddressBookGetCallback); + + worker->execute(&input); +} + +void +OAIWalletApi::privateGetAddressBookGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetAddressBookGetSignal(output); + emit privateGetAddressBookGetSignalFull(worker, output); + } else { + emit privateGetAddressBookGetSignalE(output, error_type, error_str); + emit privateGetAddressBookGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIWalletApi::privateGetCurrentDepositAddressGet(const QString& currency) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_current_deposit_address"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIWalletApi::privateGetCurrentDepositAddressGetCallback); + + worker->execute(&input); +} + +void +OAIWalletApi::privateGetCurrentDepositAddressGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetCurrentDepositAddressGetSignal(output); + emit privateGetCurrentDepositAddressGetSignalFull(worker, output); + } else { + emit privateGetCurrentDepositAddressGetSignalE(output, error_type, error_str); + emit privateGetCurrentDepositAddressGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIWalletApi::privateGetDepositsGet(const QString& currency, const qint32& count, const qint32& offset) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_deposits"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("offset")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(offset))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIWalletApi::privateGetDepositsGetCallback); + + worker->execute(&input); +} + +void +OAIWalletApi::privateGetDepositsGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetDepositsGetSignal(output); + emit privateGetDepositsGetSignalFull(worker, output); + } else { + emit privateGetDepositsGetSignalE(output, error_type, error_str); + emit privateGetDepositsGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIWalletApi::privateGetTransfersGet(const QString& currency, const qint32& count, const qint32& offset) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_transfers"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("offset")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(offset))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIWalletApi::privateGetTransfersGetCallback); + + worker->execute(&input); +} + +void +OAIWalletApi::privateGetTransfersGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetTransfersGetSignal(output); + emit privateGetTransfersGetSignalFull(worker, output); + } else { + emit privateGetTransfersGetSignalE(output, error_type, error_str); + emit privateGetTransfersGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIWalletApi::privateGetWithdrawalsGet(const QString& currency, const qint32& count, const qint32& offset) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/get_withdrawals"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("count")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(count))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("offset")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(offset))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIWalletApi::privateGetWithdrawalsGetCallback); + + worker->execute(&input); +} + +void +OAIWalletApi::privateGetWithdrawalsGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateGetWithdrawalsGetSignal(output); + emit privateGetWithdrawalsGetSignalFull(worker, output); + } else { + emit privateGetWithdrawalsGetSignalE(output, error_type, error_str); + emit privateGetWithdrawalsGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIWalletApi::privateRemoveFromAddressBookGet(const QString& currency, const QString& type, const QString& address, const QString& tfa) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/remove_from_address_book"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("type")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(type))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("address")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(address))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("tfa")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(tfa))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIWalletApi::privateRemoveFromAddressBookGetCallback); + + worker->execute(&input); +} + +void +OAIWalletApi::privateRemoveFromAddressBookGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateRemoveFromAddressBookGetSignal(output); + emit privateRemoveFromAddressBookGetSignalFull(worker, output); + } else { + emit privateRemoveFromAddressBookGetSignalE(output, error_type, error_str); + emit privateRemoveFromAddressBookGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIWalletApi::privateSubmitTransferToSubaccountGet(const QString& currency, const double& amount, const qint32& destination) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/submit_transfer_to_subaccount"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("amount")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(amount))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("destination")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(destination))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIWalletApi::privateSubmitTransferToSubaccountGetCallback); + + worker->execute(&input); +} + +void +OAIWalletApi::privateSubmitTransferToSubaccountGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateSubmitTransferToSubaccountGetSignal(output); + emit privateSubmitTransferToSubaccountGetSignalFull(worker, output); + } else { + emit privateSubmitTransferToSubaccountGetSignalE(output, error_type, error_str); + emit privateSubmitTransferToSubaccountGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIWalletApi::privateSubmitTransferToUserGet(const QString& currency, const double& amount, const QString& destination, const QString& tfa) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/submit_transfer_to_user"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("amount")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(amount))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("destination")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(destination))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("tfa")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(tfa))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIWalletApi::privateSubmitTransferToUserGetCallback); + + worker->execute(&input); +} + +void +OAIWalletApi::privateSubmitTransferToUserGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateSubmitTransferToUserGetSignal(output); + emit privateSubmitTransferToUserGetSignalFull(worker, output); + } else { + emit privateSubmitTransferToUserGetSignalE(output, error_type, error_str); + emit privateSubmitTransferToUserGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIWalletApi::privateToggleDepositAddressCreationGet(const QString& currency, const bool& state) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/toggle_deposit_address_creation"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("state")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(state))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIWalletApi::privateToggleDepositAddressCreationGetCallback); + + worker->execute(&input); +} + +void +OAIWalletApi::privateToggleDepositAddressCreationGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateToggleDepositAddressCreationGetSignal(output); + emit privateToggleDepositAddressCreationGetSignalFull(worker, output); + } else { + emit privateToggleDepositAddressCreationGetSignalE(output, error_type, error_str); + emit privateToggleDepositAddressCreationGetSignalEFull(worker, error_type, error_str); + } +} + +void +OAIWalletApi::privateWithdrawGet(const QString& currency, const QString& address, const double& amount, const QString& priority, const QString& tfa) { + QString fullPath; + fullPath.append(this->host).append(this->basePath).append("/private/withdraw"); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("currency")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(currency))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("address")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(address))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("amount")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(amount))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("priority")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(priority))); + + if (fullPath.indexOf("?") > 0) + fullPath.append("&"); + else + fullPath.append("?"); + fullPath.append(QUrl::toPercentEncoding("tfa")) + .append("=") + .append(QUrl::toPercentEncoding(::OpenAPI::toStringValue(tfa))); + + OAIHttpRequestWorker *worker = new OAIHttpRequestWorker(); + OAIHttpRequestInput input(fullPath, "GET"); + + + foreach(QString key, this->defaultHeaders.keys()) { + input.headers.insert(key, this->defaultHeaders.value(key)); + } + + connect(worker, + &OAIHttpRequestWorker::on_execution_finished, + this, + &OAIWalletApi::privateWithdrawGetCallback); + + worker->execute(&input); +} + +void +OAIWalletApi::privateWithdrawGetCallback(OAIHttpRequestWorker * worker) { + QString msg; + QString error_str = worker->error_str; + QNetworkReply::NetworkError error_type = worker->error_type; + + if (worker->error_type == QNetworkReply::NoError) { + msg = QString("Success! %1 bytes").arg(worker->response.length()); + } + else { + msg = "Error: " + worker->error_str; + } + OAIObject output(QString(worker->response)); + worker->deleteLater(); + + if (worker->error_type == QNetworkReply::NoError) { + emit privateWithdrawGetSignal(output); + emit privateWithdrawGetSignalFull(worker, output); + } else { + emit privateWithdrawGetSignalE(output, error_type, error_str); + emit privateWithdrawGetSignalEFull(worker, error_type, error_str); + } +} + + +} diff --git a/cpp-qt5-client/client/OAIWalletApi.h b/cpp-qt5-client/client/OAIWalletApi.h new file mode 100644 index 0000000..74ffe11 --- /dev/null +++ b/cpp-qt5-client/client/OAIWalletApi.h @@ -0,0 +1,135 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +#ifndef OAI_OAIWalletApi_H +#define OAI_OAIWalletApi_H + +#include "OAIHttpRequest.h" + +#include "OAIObject.h" +#include + +#include + +namespace OpenAPI { + +class OAIWalletApi: public QObject { + Q_OBJECT + +public: + OAIWalletApi(); + OAIWalletApi(const QString& host, const QString& basePath); + ~OAIWalletApi(); + + void setBasePath(const QString& basePath); + void setHost(const QString& host); + void addHeaders(const QString& key, const QString& value); + + void privateAddToAddressBookGet(const QString& currency, const QString& type, const QString& address, const QString& name, const QString& tfa); + void privateCancelTransferByIdGet(const QString& currency, const qint32& id, const QString& tfa); + void privateCancelWithdrawalGet(const QString& currency, const double& id); + void privateCreateDepositAddressGet(const QString& currency); + void privateGetAddressBookGet(const QString& currency, const QString& type); + void privateGetCurrentDepositAddressGet(const QString& currency); + void privateGetDepositsGet(const QString& currency, const qint32& count, const qint32& offset); + void privateGetTransfersGet(const QString& currency, const qint32& count, const qint32& offset); + void privateGetWithdrawalsGet(const QString& currency, const qint32& count, const qint32& offset); + void privateRemoveFromAddressBookGet(const QString& currency, const QString& type, const QString& address, const QString& tfa); + void privateSubmitTransferToSubaccountGet(const QString& currency, const double& amount, const qint32& destination); + void privateSubmitTransferToUserGet(const QString& currency, const double& amount, const QString& destination, const QString& tfa); + void privateToggleDepositAddressCreationGet(const QString& currency, const bool& state); + void privateWithdrawGet(const QString& currency, const QString& address, const double& amount, const QString& priority, const QString& tfa); + +private: + QString basePath; + QString host; + QMap defaultHeaders; + void privateAddToAddressBookGetCallback (OAIHttpRequestWorker * worker); + void privateCancelTransferByIdGetCallback (OAIHttpRequestWorker * worker); + void privateCancelWithdrawalGetCallback (OAIHttpRequestWorker * worker); + void privateCreateDepositAddressGetCallback (OAIHttpRequestWorker * worker); + void privateGetAddressBookGetCallback (OAIHttpRequestWorker * worker); + void privateGetCurrentDepositAddressGetCallback (OAIHttpRequestWorker * worker); + void privateGetDepositsGetCallback (OAIHttpRequestWorker * worker); + void privateGetTransfersGetCallback (OAIHttpRequestWorker * worker); + void privateGetWithdrawalsGetCallback (OAIHttpRequestWorker * worker); + void privateRemoveFromAddressBookGetCallback (OAIHttpRequestWorker * worker); + void privateSubmitTransferToSubaccountGetCallback (OAIHttpRequestWorker * worker); + void privateSubmitTransferToUserGetCallback (OAIHttpRequestWorker * worker); + void privateToggleDepositAddressCreationGetCallback (OAIHttpRequestWorker * worker); + void privateWithdrawGetCallback (OAIHttpRequestWorker * worker); + +signals: + void privateAddToAddressBookGetSignal(OAIObject summary); + void privateCancelTransferByIdGetSignal(OAIObject summary); + void privateCancelWithdrawalGetSignal(OAIObject summary); + void privateCreateDepositAddressGetSignal(OAIObject summary); + void privateGetAddressBookGetSignal(OAIObject summary); + void privateGetCurrentDepositAddressGetSignal(OAIObject summary); + void privateGetDepositsGetSignal(OAIObject summary); + void privateGetTransfersGetSignal(OAIObject summary); + void privateGetWithdrawalsGetSignal(OAIObject summary); + void privateRemoveFromAddressBookGetSignal(OAIObject summary); + void privateSubmitTransferToSubaccountGetSignal(OAIObject summary); + void privateSubmitTransferToUserGetSignal(OAIObject summary); + void privateToggleDepositAddressCreationGetSignal(OAIObject summary); + void privateWithdrawGetSignal(OAIObject summary); + + void privateAddToAddressBookGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateCancelTransferByIdGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateCancelWithdrawalGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateCreateDepositAddressGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetAddressBookGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetCurrentDepositAddressGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetDepositsGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetTransfersGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateGetWithdrawalsGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateRemoveFromAddressBookGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateSubmitTransferToSubaccountGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateSubmitTransferToUserGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateToggleDepositAddressCreationGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + void privateWithdrawGetSignalFull(OAIHttpRequestWorker* worker, OAIObject summary); + + void privateAddToAddressBookGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCancelTransferByIdGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCancelWithdrawalGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCreateDepositAddressGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetAddressBookGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetCurrentDepositAddressGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetDepositsGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetTransfersGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetWithdrawalsGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateRemoveFromAddressBookGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSubmitTransferToSubaccountGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSubmitTransferToUserGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateToggleDepositAddressCreationGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + void privateWithdrawGetSignalE(OAIObject summary, QNetworkReply::NetworkError error_type, QString& error_str); + + void privateAddToAddressBookGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCancelTransferByIdGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCancelWithdrawalGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateCreateDepositAddressGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetAddressBookGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetCurrentDepositAddressGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetDepositsGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetTransfersGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateGetWithdrawalsGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateRemoveFromAddressBookGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSubmitTransferToSubaccountGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateSubmitTransferToUserGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateToggleDepositAddressCreationGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + void privateWithdrawGetSignalEFull(OAIHttpRequestWorker* worker, QNetworkReply::NetworkError error_type, QString& error_str); + +}; + +} +#endif diff --git a/cpp-qt5-client/client/OAIWithdrawal.cpp b/cpp-qt5-client/client/OAIWithdrawal.cpp new file mode 100644 index 0000000..8a8fcda --- /dev/null +++ b/cpp-qt5-client/client/OAIWithdrawal.cpp @@ -0,0 +1,325 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +#include "OAIWithdrawal.h" + +#include "OAIHelpers.h" + +#include +#include +#include +#include + +namespace OpenAPI { + +OAIWithdrawal::OAIWithdrawal(QString json) { + this->init(); + this->fromJson(json); +} + +OAIWithdrawal::OAIWithdrawal() { + this->init(); +} + +OAIWithdrawal::~OAIWithdrawal() { + +} + +void +OAIWithdrawal::init() { + + m_updated_timestamp_isSet = false; + m_updated_timestamp_isValid = false; + + m_fee_isSet = false; + m_fee_isValid = false; + + m_confirmed_timestamp_isSet = false; + m_confirmed_timestamp_isValid = false; + + m_amount_isSet = false; + m_amount_isValid = false; + + m_priority_isSet = false; + m_priority_isValid = false; + + m_currency_isSet = false; + m_currency_isValid = false; + + m_state_isSet = false; + m_state_isValid = false; + + m_address_isSet = false; + m_address_isValid = false; + + m_created_timestamp_isSet = false; + m_created_timestamp_isValid = false; + + m_id_isSet = false; + m_id_isValid = false; + + m_transaction_id_isSet = false; + m_transaction_id_isValid = false; + } + +void +OAIWithdrawal::fromJson(QString jsonString) { + QByteArray array (jsonString.toStdString().c_str()); + QJsonDocument doc = QJsonDocument::fromJson(array); + QJsonObject jsonObject = doc.object(); + this->fromJsonObject(jsonObject); +} + +void +OAIWithdrawal::fromJsonObject(QJsonObject json) { + + m_updated_timestamp_isValid = ::OpenAPI::fromJsonValue(updated_timestamp, json[QString("updated_timestamp")]); + + + m_fee_isValid = ::OpenAPI::fromJsonValue(fee, json[QString("fee")]); + + + m_confirmed_timestamp_isValid = ::OpenAPI::fromJsonValue(confirmed_timestamp, json[QString("confirmed_timestamp")]); + + + m_amount_isValid = ::OpenAPI::fromJsonValue(amount, json[QString("amount")]); + + + m_priority_isValid = ::OpenAPI::fromJsonValue(priority, json[QString("priority")]); + + + m_currency_isValid = ::OpenAPI::fromJsonValue(currency, json[QString("currency")]); + + + m_state_isValid = ::OpenAPI::fromJsonValue(state, json[QString("state")]); + + + m_address_isValid = ::OpenAPI::fromJsonValue(address, json[QString("address")]); + + + m_created_timestamp_isValid = ::OpenAPI::fromJsonValue(created_timestamp, json[QString("created_timestamp")]); + + + m_id_isValid = ::OpenAPI::fromJsonValue(id, json[QString("id")]); + + + m_transaction_id_isValid = ::OpenAPI::fromJsonValue(transaction_id, json[QString("transaction_id")]); + + +} + +QString +OAIWithdrawal::asJson () const { + QJsonObject obj = this->asJsonObject(); + QJsonDocument doc(obj); + QByteArray bytes = doc.toJson(); + return QString(bytes); +} + +QJsonObject +OAIWithdrawal::asJsonObject() const { + QJsonObject obj; + if(m_updated_timestamp_isSet){ + obj.insert(QString("updated_timestamp"), ::OpenAPI::toJsonValue(updated_timestamp)); + } + if(m_fee_isSet){ + obj.insert(QString("fee"), ::OpenAPI::toJsonValue(fee)); + } + if(m_confirmed_timestamp_isSet){ + obj.insert(QString("confirmed_timestamp"), ::OpenAPI::toJsonValue(confirmed_timestamp)); + } + if(m_amount_isSet){ + obj.insert(QString("amount"), ::OpenAPI::toJsonValue(amount)); + } + if(m_priority_isSet){ + obj.insert(QString("priority"), ::OpenAPI::toJsonValue(priority)); + } + if(m_currency_isSet){ + obj.insert(QString("currency"), ::OpenAPI::toJsonValue(currency)); + } + if(m_state_isSet){ + obj.insert(QString("state"), ::OpenAPI::toJsonValue(state)); + } + if(m_address_isSet){ + obj.insert(QString("address"), ::OpenAPI::toJsonValue(address)); + } + if(m_created_timestamp_isSet){ + obj.insert(QString("created_timestamp"), ::OpenAPI::toJsonValue(created_timestamp)); + } + if(m_id_isSet){ + obj.insert(QString("id"), ::OpenAPI::toJsonValue(id)); + } + if(m_transaction_id_isSet){ + obj.insert(QString("transaction_id"), ::OpenAPI::toJsonValue(transaction_id)); + } + return obj; +} + + +qint32 +OAIWithdrawal::getUpdatedTimestamp() const { + return updated_timestamp; +} +void +OAIWithdrawal::setUpdatedTimestamp(const qint32 &updated_timestamp) { + this->updated_timestamp = updated_timestamp; + this->m_updated_timestamp_isSet = true; +} + + +double +OAIWithdrawal::getFee() const { + return fee; +} +void +OAIWithdrawal::setFee(const double &fee) { + this->fee = fee; + this->m_fee_isSet = true; +} + + +qint32 +OAIWithdrawal::getConfirmedTimestamp() const { + return confirmed_timestamp; +} +void +OAIWithdrawal::setConfirmedTimestamp(const qint32 &confirmed_timestamp) { + this->confirmed_timestamp = confirmed_timestamp; + this->m_confirmed_timestamp_isSet = true; +} + + +double +OAIWithdrawal::getAmount() const { + return amount; +} +void +OAIWithdrawal::setAmount(const double &amount) { + this->amount = amount; + this->m_amount_isSet = true; +} + + +double +OAIWithdrawal::getPriority() const { + return priority; +} +void +OAIWithdrawal::setPriority(const double &priority) { + this->priority = priority; + this->m_priority_isSet = true; +} + + +QString +OAIWithdrawal::getCurrency() const { + return currency; +} +void +OAIWithdrawal::setCurrency(const QString ¤cy) { + this->currency = currency; + this->m_currency_isSet = true; +} + + +QString +OAIWithdrawal::getState() const { + return state; +} +void +OAIWithdrawal::setState(const QString &state) { + this->state = state; + this->m_state_isSet = true; +} + + +QString +OAIWithdrawal::getAddress() const { + return address; +} +void +OAIWithdrawal::setAddress(const QString &address) { + this->address = address; + this->m_address_isSet = true; +} + + +qint32 +OAIWithdrawal::getCreatedTimestamp() const { + return created_timestamp; +} +void +OAIWithdrawal::setCreatedTimestamp(const qint32 &created_timestamp) { + this->created_timestamp = created_timestamp; + this->m_created_timestamp_isSet = true; +} + + +qint32 +OAIWithdrawal::getId() const { + return id; +} +void +OAIWithdrawal::setId(const qint32 &id) { + this->id = id; + this->m_id_isSet = true; +} + + +QString +OAIWithdrawal::getTransactionId() const { + return transaction_id; +} +void +OAIWithdrawal::setTransactionId(const QString &transaction_id) { + this->transaction_id = transaction_id; + this->m_transaction_id_isSet = true; +} + +bool +OAIWithdrawal::isSet() const { + bool isObjectUpdated = false; + do{ + if(m_updated_timestamp_isSet){ isObjectUpdated = true; break;} + + if(m_fee_isSet){ isObjectUpdated = true; break;} + + if(m_confirmed_timestamp_isSet){ isObjectUpdated = true; break;} + + if(m_amount_isSet){ isObjectUpdated = true; break;} + + if(m_priority_isSet){ isObjectUpdated = true; break;} + + if(m_currency_isSet){ isObjectUpdated = true; break;} + + if(m_state_isSet){ isObjectUpdated = true; break;} + + if(m_address_isSet){ isObjectUpdated = true; break;} + + if(m_created_timestamp_isSet){ isObjectUpdated = true; break;} + + if(m_id_isSet){ isObjectUpdated = true; break;} + + if(m_transaction_id_isSet){ isObjectUpdated = true; break;} + }while(false); + return isObjectUpdated; +} + +bool +OAIWithdrawal::isValid() const { + // only required properties are required for the object to be considered valid + return m_updated_timestamp_isValid && m_amount_isValid && m_currency_isValid && m_state_isValid && m_address_isValid && m_transaction_id_isValid && true; +} + +} + diff --git a/cpp-qt5-client/client/OAIWithdrawal.h b/cpp-qt5-client/client/OAIWithdrawal.h new file mode 100644 index 0000000..68cbff1 --- /dev/null +++ b/cpp-qt5-client/client/OAIWithdrawal.h @@ -0,0 +1,143 @@ +/** + * Deribit API + * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods + * + * The version of the OpenAPI document: 2.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +/* + * OAIWithdrawal.h + * + * + */ + +#ifndef OAIWithdrawal_H +#define OAIWithdrawal_H + +#include + + +#include + +#include "OAIObject.h" +#include "OAIEnum.h" + +namespace OpenAPI { + +class OAIWithdrawal: public OAIObject { +public: + OAIWithdrawal(); + OAIWithdrawal(QString json); + ~OAIWithdrawal() override; + + QString asJson () const override; + QJsonObject asJsonObject() const override; + void fromJsonObject(QJsonObject json) override; + void fromJson(QString jsonString) override; + + + qint32 getUpdatedTimestamp() const; + void setUpdatedTimestamp(const qint32 &updated_timestamp); + + + double getFee() const; + void setFee(const double &fee); + + + qint32 getConfirmedTimestamp() const; + void setConfirmedTimestamp(const qint32 &confirmed_timestamp); + + + double getAmount() const; + void setAmount(const double &amount); + + + double getPriority() const; + void setPriority(const double &priority); + + + QString getCurrency() const; + void setCurrency(const QString ¤cy); + + + QString getState() const; + void setState(const QString &state); + + + QString getAddress() const; + void setAddress(const QString &address); + + + qint32 getCreatedTimestamp() const; + void setCreatedTimestamp(const qint32 &created_timestamp); + + + qint32 getId() const; + void setId(const qint32 &id); + + + QString getTransactionId() const; + void setTransactionId(const QString &transaction_id); + + + + virtual bool isSet() const override; + virtual bool isValid() const override; + +private: + void init(); + + qint32 updated_timestamp; + bool m_updated_timestamp_isSet; + bool m_updated_timestamp_isValid; + + double fee; + bool m_fee_isSet; + bool m_fee_isValid; + + qint32 confirmed_timestamp; + bool m_confirmed_timestamp_isSet; + bool m_confirmed_timestamp_isValid; + + double amount; + bool m_amount_isSet; + bool m_amount_isValid; + + double priority; + bool m_priority_isSet; + bool m_priority_isValid; + + QString currency; + bool m_currency_isSet; + bool m_currency_isValid; + + QString state; + bool m_state_isSet; + bool m_state_isValid; + + QString address; + bool m_address_isSet; + bool m_address_isValid; + + qint32 created_timestamp; + bool m_created_timestamp_isSet; + bool m_created_timestamp_isValid; + + qint32 id; + bool m_id_isSet; + bool m_id_isValid; + + QString transaction_id; + bool m_transaction_id_isSet; + bool m_transaction_id_isValid; + + }; + +} + +#endif // OAIWithdrawal_H diff --git a/cpp-qt5-client/client/client.pri b/cpp-qt5-client/client/client.pri new file mode 100644 index 0000000..f7693b4 --- /dev/null +++ b/cpp-qt5-client/client/client.pri @@ -0,0 +1,76 @@ +QT += network + +HEADERS += \ +# Models + $${PWD}/OAIAddress_book_item.h \ + $${PWD}/OAIBook_summary.h \ + $${PWD}/OAICurrency.h \ + $${PWD}/OAICurrency_portfolio.h \ + $${PWD}/OAICurrency_withdrawal_priorities.h \ + $${PWD}/OAIDeposit.h \ + $${PWD}/OAIInstrument.h \ + $${PWD}/OAIKey_number_pair.h \ + $${PWD}/OAIOrder.h \ + $${PWD}/OAIOrder_id_initial_margin_pair.h \ + $${PWD}/OAIPortfolio.h \ + $${PWD}/OAIPortfolio_eth.h \ + $${PWD}/OAIPosition.h \ + $${PWD}/OAIPublic_trade.h \ + $${PWD}/OAISettlement.h \ + $${PWD}/OAITrades_volumes.h \ + $${PWD}/OAITransfer_item.h \ + $${PWD}/OAITypes.h \ + $${PWD}/OAIUser_trade.h \ + $${PWD}/OAIWithdrawal.h \ +# APIs + $${PWD}/OAIAccountManagementApi.h \ + $${PWD}/OAIAuthenticationApi.h \ + $${PWD}/OAIInternalApi.h \ + $${PWD}/OAIMarketDataApi.h \ + $${PWD}/OAIPrivateApi.h \ + $${PWD}/OAIPublicApi.h \ + $${PWD}/OAISupportingApi.h \ + $${PWD}/OAITradingApi.h \ + $${PWD}/OAIWalletApi.h \ +# Others + $${PWD}/OAIHelpers.h \ + $${PWD}/OAIHttpRequest.h \ + $${PWD}/OAIObject.h + $${PWD}/OAIEnum.h + +SOURCES += \ +# Models + $${PWD}/OAIAddress_book_item.cpp \ + $${PWD}/OAIBook_summary.cpp \ + $${PWD}/OAICurrency.cpp \ + $${PWD}/OAICurrency_portfolio.cpp \ + $${PWD}/OAICurrency_withdrawal_priorities.cpp \ + $${PWD}/OAIDeposit.cpp \ + $${PWD}/OAIInstrument.cpp \ + $${PWD}/OAIKey_number_pair.cpp \ + $${PWD}/OAIOrder.cpp \ + $${PWD}/OAIOrder_id_initial_margin_pair.cpp \ + $${PWD}/OAIPortfolio.cpp \ + $${PWD}/OAIPortfolio_eth.cpp \ + $${PWD}/OAIPosition.cpp \ + $${PWD}/OAIPublic_trade.cpp \ + $${PWD}/OAISettlement.cpp \ + $${PWD}/OAITrades_volumes.cpp \ + $${PWD}/OAITransfer_item.cpp \ + $${PWD}/OAITypes.cpp \ + $${PWD}/OAIUser_trade.cpp \ + $${PWD}/OAIWithdrawal.cpp \ +# APIs + $${PWD}/OAIAccountManagementApi.cpp \ + $${PWD}/OAIAuthenticationApi.cpp \ + $${PWD}/OAIInternalApi.cpp \ + $${PWD}/OAIMarketDataApi.cpp \ + $${PWD}/OAIPrivateApi.cpp \ + $${PWD}/OAIPublicApi.cpp \ + $${PWD}/OAISupportingApi.cpp \ + $${PWD}/OAITradingApi.cpp \ + $${PWD}/OAIWalletApi.cpp \ +# Others + $${PWD}/OAIHelpers.cpp \ + $${PWD}/OAIHttpRequest.cpp + diff --git a/cpp-restsdk/.openapi-generator/VERSION b/cpp-restsdk/.openapi-generator/VERSION index afa6365..d96260b 100644 --- a/cpp-restsdk/.openapi-generator/VERSION +++ b/cpp-restsdk/.openapi-generator/VERSION @@ -1 +1 @@ -4.0.0-SNAPSHOT \ No newline at end of file +4.0.2-SNAPSHOT \ No newline at end of file diff --git a/cpp-restsdk/ApiClient.cpp b/cpp-restsdk/ApiClient.cpp index d2e4f83..65e5e50 100644 --- a/cpp-restsdk/ApiClient.cpp +++ b/cpp-restsdk/ApiClient.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/ApiClient.h b/cpp-restsdk/ApiClient.h index 2555dc6..5ac879e 100644 --- a/cpp-restsdk/ApiClient.h +++ b/cpp-restsdk/ApiClient.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/ApiConfiguration.cpp b/cpp-restsdk/ApiConfiguration.cpp index 46c3c6a..85f9248 100644 --- a/cpp-restsdk/ApiConfiguration.cpp +++ b/cpp-restsdk/ApiConfiguration.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/ApiConfiguration.h b/cpp-restsdk/ApiConfiguration.h index 1e11c5c..23c46aa 100644 --- a/cpp-restsdk/ApiConfiguration.h +++ b/cpp-restsdk/ApiConfiguration.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/ApiException.cpp b/cpp-restsdk/ApiException.cpp index e1b08bd..19ba065 100644 --- a/cpp-restsdk/ApiException.cpp +++ b/cpp-restsdk/ApiException.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/ApiException.h b/cpp-restsdk/ApiException.h index 81c02dd..7f801a3 100644 --- a/cpp-restsdk/ApiException.h +++ b/cpp-restsdk/ApiException.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/CMakeLists.txt b/cpp-restsdk/CMakeLists.txt index 83a5fee..0fd9c92 100644 --- a/cpp-restsdk/CMakeLists.txt +++ b/cpp-restsdk/CMakeLists.txt @@ -2,7 +2,7 @@ # Deribit API # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 1.0.0 +# The version of the OpenAPI document: 1.0.0 # # https://openapi-generator.tech # diff --git a/cpp-restsdk/HttpContent.cpp b/cpp-restsdk/HttpContent.cpp index 7d52c65..de44c6e 100644 --- a/cpp-restsdk/HttpContent.cpp +++ b/cpp-restsdk/HttpContent.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/HttpContent.h b/cpp-restsdk/HttpContent.h index fe1c814..a6e20a9 100644 --- a/cpp-restsdk/HttpContent.h +++ b/cpp-restsdk/HttpContent.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/IHttpBody.h b/cpp-restsdk/IHttpBody.h index 892136e..c8def2d 100644 --- a/cpp-restsdk/IHttpBody.h +++ b/cpp-restsdk/IHttpBody.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/JsonBody.cpp b/cpp-restsdk/JsonBody.cpp index e556c79..6987b5a 100644 --- a/cpp-restsdk/JsonBody.cpp +++ b/cpp-restsdk/JsonBody.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/JsonBody.h b/cpp-restsdk/JsonBody.h index ff5454c..d029444 100644 --- a/cpp-restsdk/JsonBody.h +++ b/cpp-restsdk/JsonBody.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/ModelBase.cpp b/cpp-restsdk/ModelBase.cpp index 841aba3..14c16da 100644 --- a/cpp-restsdk/ModelBase.cpp +++ b/cpp-restsdk/ModelBase.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/ModelBase.h b/cpp-restsdk/ModelBase.h index 66badd2..64952df 100644 --- a/cpp-restsdk/ModelBase.h +++ b/cpp-restsdk/ModelBase.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/MultipartFormData.cpp b/cpp-restsdk/MultipartFormData.cpp index 3ce4766..cbe944e 100644 --- a/cpp-restsdk/MultipartFormData.cpp +++ b/cpp-restsdk/MultipartFormData.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/MultipartFormData.h b/cpp-restsdk/MultipartFormData.h index a3c822f..f804b80 100644 --- a/cpp-restsdk/MultipartFormData.h +++ b/cpp-restsdk/MultipartFormData.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/Object.cpp b/cpp-restsdk/Object.cpp index 06fb6a9..5e179e9 100644 --- a/cpp-restsdk/Object.cpp +++ b/cpp-restsdk/Object.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/Object.h b/cpp-restsdk/Object.h index 43ed7a2..6537706 100644 --- a/cpp-restsdk/Object.h +++ b/cpp-restsdk/Object.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/api/AccountManagementApi.cpp b/cpp-restsdk/api/AccountManagementApi.cpp index 6415012..6cdf48c 100644 --- a/cpp-restsdk/api/AccountManagementApi.cpp +++ b/cpp-restsdk/api/AccountManagementApi.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/api/AccountManagementApi.h b/cpp-restsdk/api/AccountManagementApi.h index ba451f7..62d6805 100644 --- a/cpp-restsdk/api/AccountManagementApi.h +++ b/cpp-restsdk/api/AccountManagementApi.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/api/AuthenticationApi.cpp b/cpp-restsdk/api/AuthenticationApi.cpp index 40e150d..309bd62 100644 --- a/cpp-restsdk/api/AuthenticationApi.cpp +++ b/cpp-restsdk/api/AuthenticationApi.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/api/AuthenticationApi.h b/cpp-restsdk/api/AuthenticationApi.h index cc143af..6c3ae6c 100644 --- a/cpp-restsdk/api/AuthenticationApi.h +++ b/cpp-restsdk/api/AuthenticationApi.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/api/InternalApi.cpp b/cpp-restsdk/api/InternalApi.cpp index 6c77770..7b74848 100644 --- a/cpp-restsdk/api/InternalApi.cpp +++ b/cpp-restsdk/api/InternalApi.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/api/InternalApi.h b/cpp-restsdk/api/InternalApi.h index cf88746..96b4b08 100644 --- a/cpp-restsdk/api/InternalApi.h +++ b/cpp-restsdk/api/InternalApi.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/api/MarketDataApi.cpp b/cpp-restsdk/api/MarketDataApi.cpp index 609cc68..642b5e6 100644 --- a/cpp-restsdk/api/MarketDataApi.cpp +++ b/cpp-restsdk/api/MarketDataApi.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/api/MarketDataApi.h b/cpp-restsdk/api/MarketDataApi.h index b4eacdd..26a85e6 100644 --- a/cpp-restsdk/api/MarketDataApi.h +++ b/cpp-restsdk/api/MarketDataApi.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/api/PrivateApi.cpp b/cpp-restsdk/api/PrivateApi.cpp index e750d5d..de4d15b 100644 --- a/cpp-restsdk/api/PrivateApi.cpp +++ b/cpp-restsdk/api/PrivateApi.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/api/PrivateApi.h b/cpp-restsdk/api/PrivateApi.h index 0a41ab4..646c00e 100644 --- a/cpp-restsdk/api/PrivateApi.h +++ b/cpp-restsdk/api/PrivateApi.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/api/PublicApi.cpp b/cpp-restsdk/api/PublicApi.cpp index 64fd589..6c685db 100644 --- a/cpp-restsdk/api/PublicApi.cpp +++ b/cpp-restsdk/api/PublicApi.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/api/PublicApi.h b/cpp-restsdk/api/PublicApi.h index 90b3a21..2cb4e1b 100644 --- a/cpp-restsdk/api/PublicApi.h +++ b/cpp-restsdk/api/PublicApi.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/api/SupportingApi.cpp b/cpp-restsdk/api/SupportingApi.cpp index f080b98..8fec716 100644 --- a/cpp-restsdk/api/SupportingApi.cpp +++ b/cpp-restsdk/api/SupportingApi.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/api/SupportingApi.h b/cpp-restsdk/api/SupportingApi.h index ffcbf9d..03b9a25 100644 --- a/cpp-restsdk/api/SupportingApi.h +++ b/cpp-restsdk/api/SupportingApi.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/api/TradingApi.cpp b/cpp-restsdk/api/TradingApi.cpp index c8bd2f7..4b450a2 100644 --- a/cpp-restsdk/api/TradingApi.cpp +++ b/cpp-restsdk/api/TradingApi.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/api/TradingApi.h b/cpp-restsdk/api/TradingApi.h index defeca4..055b911 100644 --- a/cpp-restsdk/api/TradingApi.h +++ b/cpp-restsdk/api/TradingApi.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/api/WalletApi.cpp b/cpp-restsdk/api/WalletApi.cpp index ca48d79..a76417f 100644 --- a/cpp-restsdk/api/WalletApi.cpp +++ b/cpp-restsdk/api/WalletApi.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/api/WalletApi.h b/cpp-restsdk/api/WalletApi.h index d70e0fd..d7adb69 100644 --- a/cpp-restsdk/api/WalletApi.h +++ b/cpp-restsdk/api/WalletApi.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Address_book_item.cpp b/cpp-restsdk/model/Address_book_item.cpp index c6c1aa4..87f14c2 100644 --- a/cpp-restsdk/model/Address_book_item.cpp +++ b/cpp-restsdk/model/Address_book_item.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Address_book_item.h b/cpp-restsdk/model/Address_book_item.h index 94af958..6f5d6f3 100644 --- a/cpp-restsdk/model/Address_book_item.h +++ b/cpp-restsdk/model/Address_book_item.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Book_summary.cpp b/cpp-restsdk/model/Book_summary.cpp index 8c54e92..6fb8a0d 100644 --- a/cpp-restsdk/model/Book_summary.cpp +++ b/cpp-restsdk/model/Book_summary.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Book_summary.h b/cpp-restsdk/model/Book_summary.h index 0f09b7c..c908797 100644 --- a/cpp-restsdk/model/Book_summary.h +++ b/cpp-restsdk/model/Book_summary.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Currency.cpp b/cpp-restsdk/model/Currency.cpp index 6214013..75e5cf0 100644 --- a/cpp-restsdk/model/Currency.cpp +++ b/cpp-restsdk/model/Currency.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Currency.h b/cpp-restsdk/model/Currency.h index 4970f6f..96544d9 100644 --- a/cpp-restsdk/model/Currency.h +++ b/cpp-restsdk/model/Currency.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Currency_portfolio.cpp b/cpp-restsdk/model/Currency_portfolio.cpp index cb0085b..3459384 100644 --- a/cpp-restsdk/model/Currency_portfolio.cpp +++ b/cpp-restsdk/model/Currency_portfolio.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Currency_portfolio.h b/cpp-restsdk/model/Currency_portfolio.h index 78afd89..6b8a95d 100644 --- a/cpp-restsdk/model/Currency_portfolio.h +++ b/cpp-restsdk/model/Currency_portfolio.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Currency_withdrawal_priorities.cpp b/cpp-restsdk/model/Currency_withdrawal_priorities.cpp index a39c6fc..d14f848 100644 --- a/cpp-restsdk/model/Currency_withdrawal_priorities.cpp +++ b/cpp-restsdk/model/Currency_withdrawal_priorities.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Currency_withdrawal_priorities.h b/cpp-restsdk/model/Currency_withdrawal_priorities.h index 08cc8e6..94e2119 100644 --- a/cpp-restsdk/model/Currency_withdrawal_priorities.h +++ b/cpp-restsdk/model/Currency_withdrawal_priorities.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Deposit.cpp b/cpp-restsdk/model/Deposit.cpp index 713ae23..4fc3558 100644 --- a/cpp-restsdk/model/Deposit.cpp +++ b/cpp-restsdk/model/Deposit.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Deposit.h b/cpp-restsdk/model/Deposit.h index b03705f..6ac543d 100644 --- a/cpp-restsdk/model/Deposit.h +++ b/cpp-restsdk/model/Deposit.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Instrument.cpp b/cpp-restsdk/model/Instrument.cpp index 8a5c272..b81b10d 100644 --- a/cpp-restsdk/model/Instrument.cpp +++ b/cpp-restsdk/model/Instrument.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Instrument.h b/cpp-restsdk/model/Instrument.h index 33def23..f286813 100644 --- a/cpp-restsdk/model/Instrument.h +++ b/cpp-restsdk/model/Instrument.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Key_number_pair.cpp b/cpp-restsdk/model/Key_number_pair.cpp index 0964953..1c87638 100644 --- a/cpp-restsdk/model/Key_number_pair.cpp +++ b/cpp-restsdk/model/Key_number_pair.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Key_number_pair.h b/cpp-restsdk/model/Key_number_pair.h index 70cb69f..e2f0aa6 100644 --- a/cpp-restsdk/model/Key_number_pair.h +++ b/cpp-restsdk/model/Key_number_pair.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Order.cpp b/cpp-restsdk/model/Order.cpp index c466453..f71bf30 100644 --- a/cpp-restsdk/model/Order.cpp +++ b/cpp-restsdk/model/Order.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Order.h b/cpp-restsdk/model/Order.h index acc7185..a56354a 100644 --- a/cpp-restsdk/model/Order.h +++ b/cpp-restsdk/model/Order.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Order_id_initial_margin_pair.cpp b/cpp-restsdk/model/Order_id_initial_margin_pair.cpp index 103245e..43fd12a 100644 --- a/cpp-restsdk/model/Order_id_initial_margin_pair.cpp +++ b/cpp-restsdk/model/Order_id_initial_margin_pair.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Order_id_initial_margin_pair.h b/cpp-restsdk/model/Order_id_initial_margin_pair.h index 9f9f2f8..75fc3ae 100644 --- a/cpp-restsdk/model/Order_id_initial_margin_pair.h +++ b/cpp-restsdk/model/Order_id_initial_margin_pair.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Portfolio.cpp b/cpp-restsdk/model/Portfolio.cpp index 2ec90eb..6dcbc3d 100644 --- a/cpp-restsdk/model/Portfolio.cpp +++ b/cpp-restsdk/model/Portfolio.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Portfolio.h b/cpp-restsdk/model/Portfolio.h index 932bb18..a7d70bd 100644 --- a/cpp-restsdk/model/Portfolio.h +++ b/cpp-restsdk/model/Portfolio.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Portfolio_eth.cpp b/cpp-restsdk/model/Portfolio_eth.cpp index 055d67d..f1396f4 100644 --- a/cpp-restsdk/model/Portfolio_eth.cpp +++ b/cpp-restsdk/model/Portfolio_eth.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Portfolio_eth.h b/cpp-restsdk/model/Portfolio_eth.h index 2d3cacb..26f2f82 100644 --- a/cpp-restsdk/model/Portfolio_eth.h +++ b/cpp-restsdk/model/Portfolio_eth.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Position.cpp b/cpp-restsdk/model/Position.cpp index b18d3af..7d6e96c 100644 --- a/cpp-restsdk/model/Position.cpp +++ b/cpp-restsdk/model/Position.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Position.h b/cpp-restsdk/model/Position.h index d76e42f..7547cef 100644 --- a/cpp-restsdk/model/Position.h +++ b/cpp-restsdk/model/Position.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Public_trade.cpp b/cpp-restsdk/model/Public_trade.cpp index 3dc2f9b..9123669 100644 --- a/cpp-restsdk/model/Public_trade.cpp +++ b/cpp-restsdk/model/Public_trade.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Public_trade.h b/cpp-restsdk/model/Public_trade.h index b8225fd..1def3e4 100644 --- a/cpp-restsdk/model/Public_trade.h +++ b/cpp-restsdk/model/Public_trade.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Settlement.cpp b/cpp-restsdk/model/Settlement.cpp index 485d5b5..4fc5da9 100644 --- a/cpp-restsdk/model/Settlement.cpp +++ b/cpp-restsdk/model/Settlement.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Settlement.h b/cpp-restsdk/model/Settlement.h index abf9d0b..72d720d 100644 --- a/cpp-restsdk/model/Settlement.h +++ b/cpp-restsdk/model/Settlement.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Trades_volumes.cpp b/cpp-restsdk/model/Trades_volumes.cpp index 9b0def7..1fd70b5 100644 --- a/cpp-restsdk/model/Trades_volumes.cpp +++ b/cpp-restsdk/model/Trades_volumes.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Trades_volumes.h b/cpp-restsdk/model/Trades_volumes.h index 16e7f74..ff1bdc4 100644 --- a/cpp-restsdk/model/Trades_volumes.h +++ b/cpp-restsdk/model/Trades_volumes.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Transfer_item.cpp b/cpp-restsdk/model/Transfer_item.cpp index ea76beb..2f04898 100644 --- a/cpp-restsdk/model/Transfer_item.cpp +++ b/cpp-restsdk/model/Transfer_item.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Transfer_item.h b/cpp-restsdk/model/Transfer_item.h index 30166ae..f6f8c4f 100644 --- a/cpp-restsdk/model/Transfer_item.h +++ b/cpp-restsdk/model/Transfer_item.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Types.cpp b/cpp-restsdk/model/Types.cpp index c28e9c2..80679db 100644 --- a/cpp-restsdk/model/Types.cpp +++ b/cpp-restsdk/model/Types.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Types.h b/cpp-restsdk/model/Types.h index 352920b..a38a046 100644 --- a/cpp-restsdk/model/Types.h +++ b/cpp-restsdk/model/Types.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/User_trade.cpp b/cpp-restsdk/model/User_trade.cpp index e0f3922..21b58f8 100644 --- a/cpp-restsdk/model/User_trade.cpp +++ b/cpp-restsdk/model/User_trade.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/User_trade.h b/cpp-restsdk/model/User_trade.h index f31c6c7..0dd0f3b 100644 --- a/cpp-restsdk/model/User_trade.h +++ b/cpp-restsdk/model/User_trade.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Withdrawal.cpp b/cpp-restsdk/model/Withdrawal.cpp index 0a74f1d..9d13adc 100644 --- a/cpp-restsdk/model/Withdrawal.cpp +++ b/cpp-restsdk/model/Withdrawal.cpp @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/cpp-restsdk/model/Withdrawal.h b/cpp-restsdk/model/Withdrawal.h index f2396e3..b44f78a 100644 --- a/cpp-restsdk/model/Withdrawal.h +++ b/cpp-restsdk/model/Withdrawal.h @@ -2,9 +2,9 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 4.0.2-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/csharp/.openapi-generator/VERSION b/csharp/.openapi-generator/VERSION index afa6365..d96260b 100644 --- a/csharp/.openapi-generator/VERSION +++ b/csharp/.openapi-generator/VERSION @@ -1 +1 @@ -4.0.0-SNAPSHOT \ No newline at end of file +4.0.2-SNAPSHOT \ No newline at end of file diff --git a/csharp/Org.OpenAPITools.sln b/csharp/Org.OpenAPITools.sln index fd89561..0b20c2a 100644 --- a/csharp/Org.OpenAPITools.sln +++ b/csharp/Org.OpenAPITools.sln @@ -2,7 +2,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 VisualStudioVersion = 12.0.0.0 MinimumVisualStudioVersion = 10.0.0.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools", "src\Org.OpenAPITools\Org.OpenAPITools.csproj", "{5F75563A-5FF8-4B20-8CE6-D15261CAA864}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools", "src\Org.OpenAPITools\Org.OpenAPITools.csproj", "{0B21CDEF-66B6-42CD-AE10-89BC72BA5CDB}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools.Test", "src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" EndProject @@ -12,10 +12,10 @@ Global Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution - {5F75563A-5FF8-4B20-8CE6-D15261CAA864}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5F75563A-5FF8-4B20-8CE6-D15261CAA864}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5F75563A-5FF8-4B20-8CE6-D15261CAA864}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5F75563A-5FF8-4B20-8CE6-D15261CAA864}.Release|Any CPU.Build.0 = Release|Any CPU + {0B21CDEF-66B6-42CD-AE10-89BC72BA5CDB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0B21CDEF-66B6-42CD-AE10-89BC72BA5CDB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0B21CDEF-66B6-42CD-AE10-89BC72BA5CDB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0B21CDEF-66B6-42CD-AE10-89BC72BA5CDB}.Release|Any CPU.Build.0 = Release|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/csharp/README.md b/csharp/README.md index 11a241e..735c25f 100644 --- a/csharp/README.md +++ b/csharp/README.md @@ -64,7 +64,6 @@ Then, publish to a [local feed](https://docs.microsoft.com/en-us/nuget/hosting-p ## Getting Started ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -74,14 +73,15 @@ namespace Example { public class Example { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new AccountManagementApi(); + var apiInstance = new AccountManagementApi(Configuration.Default); var sid = 56; // int? | The user id for the subaccount var name = newUserName; // string | The new user name @@ -91,9 +91,11 @@ namespace Example Object result = apiInstance.PrivateChangeSubaccountNameGet(sid, name); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling AccountManagementApi.PrivateChangeSubaccountNameGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } diff --git a/csharp/docs/AccountManagementApi.md b/csharp/docs/AccountManagementApi.md index 0f15424..bd5d948 100644 --- a/csharp/docs/AccountManagementApi.md +++ b/csharp/docs/AccountManagementApi.md @@ -32,7 +32,6 @@ Change the user name for a subaccount ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -42,13 +41,14 @@ namespace Example { public class PrivateChangeSubaccountNameGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new AccountManagementApi(); + var apiInstance = new AccountManagementApi(Configuration.Default); var sid = 56; // int? | The user id for the subaccount var name = newUserName; // string | The new user name @@ -58,9 +58,11 @@ namespace Example Object result = apiInstance.PrivateChangeSubaccountNameGet(sid, name); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling AccountManagementApi.PrivateChangeSubaccountNameGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -103,7 +105,6 @@ Create a new subaccount ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -113,13 +114,14 @@ namespace Example { public class PrivateCreateSubaccountGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new AccountManagementApi(); + var apiInstance = new AccountManagementApi(Configuration.Default); try { @@ -127,9 +129,11 @@ namespace Example Object result = apiInstance.PrivateCreateSubaccountGet(); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling AccountManagementApi.PrivateCreateSubaccountGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -168,7 +172,6 @@ Disable two factor authentication for a subaccount. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -178,13 +181,14 @@ namespace Example { public class PrivateDisableTfaForSubaccountGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new AccountManagementApi(); + var apiInstance = new AccountManagementApi(Configuration.Default); var sid = 56; // int? | The user id for the subaccount try @@ -193,9 +197,11 @@ namespace Example Object result = apiInstance.PrivateDisableTfaForSubaccountGet(sid); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling AccountManagementApi.PrivateDisableTfaForSubaccountGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -237,7 +243,6 @@ Retrieves user account summary. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -247,13 +252,14 @@ namespace Example { public class PrivateGetAccountSummaryGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new AccountManagementApi(); + var apiInstance = new AccountManagementApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var extended = false; // bool? | Include additional fields (optional) @@ -263,9 +269,11 @@ namespace Example Object result = apiInstance.PrivateGetAccountSummaryGet(currency, extended); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling AccountManagementApi.PrivateGetAccountSummaryGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -308,7 +316,6 @@ Retrieves the language to be used for emails. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -318,13 +325,14 @@ namespace Example { public class PrivateGetEmailLanguageGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new AccountManagementApi(); + var apiInstance = new AccountManagementApi(Configuration.Default); try { @@ -332,9 +340,11 @@ namespace Example Object result = apiInstance.PrivateGetEmailLanguageGet(); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling AccountManagementApi.PrivateGetEmailLanguageGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -373,7 +383,6 @@ Retrieves announcements that have not been marked read by the user. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -383,13 +392,14 @@ namespace Example { public class PrivateGetNewAnnouncementsGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new AccountManagementApi(); + var apiInstance = new AccountManagementApi(Configuration.Default); try { @@ -397,9 +407,11 @@ namespace Example Object result = apiInstance.PrivateGetNewAnnouncementsGet(); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling AccountManagementApi.PrivateGetNewAnnouncementsGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -438,7 +450,6 @@ Retrieve user position. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -448,13 +459,14 @@ namespace Example { public class PrivateGetPositionGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new AccountManagementApi(); + var apiInstance = new AccountManagementApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name try @@ -463,9 +475,11 @@ namespace Example Object result = apiInstance.PrivateGetPositionGet(instrumentName); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling AccountManagementApi.PrivateGetPositionGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -507,7 +521,6 @@ Retrieve user positions. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -517,13 +530,14 @@ namespace Example { public class PrivateGetPositionsGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new AccountManagementApi(); + var apiInstance = new AccountManagementApi(Configuration.Default); var currency = currency_example; // string | var kind = kind_example; // string | Kind filter on positions (optional) @@ -533,9 +547,11 @@ namespace Example Object result = apiInstance.PrivateGetPositionsGet(currency, kind); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling AccountManagementApi.PrivateGetPositionsGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -578,7 +594,6 @@ Get information about subaccounts ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -588,13 +603,14 @@ namespace Example { public class PrivateGetSubaccountsGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new AccountManagementApi(); + var apiInstance = new AccountManagementApi(Configuration.Default); var withPortfolio = true; // bool? | (optional) try @@ -603,9 +619,11 @@ namespace Example Object result = apiInstance.PrivateGetSubaccountsGet(withPortfolio); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling AccountManagementApi.PrivateGetSubaccountsGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -647,7 +665,6 @@ Marks an announcement as read, so it will not be shown in `get_new_announcements ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -657,13 +674,14 @@ namespace Example { public class PrivateSetAnnouncementAsReadGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new AccountManagementApi(); + var apiInstance = new AccountManagementApi(Configuration.Default); var announcementId = 8.14; // decimal? | the ID of the announcement try @@ -672,9 +690,11 @@ namespace Example Object result = apiInstance.PrivateSetAnnouncementAsReadGet(announcementId); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling AccountManagementApi.PrivateSetAnnouncementAsReadGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -716,7 +736,6 @@ Assign an email address to a subaccount. User will receive an email with confirm ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -726,13 +745,14 @@ namespace Example { public class PrivateSetEmailForSubaccountGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new AccountManagementApi(); + var apiInstance = new AccountManagementApi(Configuration.Default); var sid = 56; // int? | The user id for the subaccount var email = subaccount_1@email.com; // string | The email address for the subaccount @@ -742,9 +762,11 @@ namespace Example Object result = apiInstance.PrivateSetEmailForSubaccountGet(sid, email); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling AccountManagementApi.PrivateSetEmailForSubaccountGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -787,7 +809,6 @@ Changes the language to be used for emails. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -797,13 +818,14 @@ namespace Example { public class PrivateSetEmailLanguageGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new AccountManagementApi(); + var apiInstance = new AccountManagementApi(Configuration.Default); var language = en; // string | The abbreviated language name. Valid values include `\"en\"`, `\"ko\"`, `\"zh\"` try @@ -812,9 +834,11 @@ namespace Example Object result = apiInstance.PrivateSetEmailLanguageGet(language); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling AccountManagementApi.PrivateSetEmailLanguageGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -856,7 +880,6 @@ Set the password for the subaccount ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -866,13 +889,14 @@ namespace Example { public class PrivateSetPasswordForSubaccountGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new AccountManagementApi(); + var apiInstance = new AccountManagementApi(Configuration.Default); var sid = 56; // int? | The user id for the subaccount var password = password_example; // string | The password for the subaccount @@ -882,9 +906,11 @@ namespace Example Object result = apiInstance.PrivateSetPasswordForSubaccountGet(sid, password); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling AccountManagementApi.PrivateSetPasswordForSubaccountGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -927,7 +953,6 @@ Enable or disable sending of notifications for the subaccount. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -937,13 +962,14 @@ namespace Example { public class PrivateToggleNotificationsFromSubaccountGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new AccountManagementApi(); + var apiInstance = new AccountManagementApi(Configuration.Default); var sid = 56; // int? | The user id for the subaccount var state = true; // bool? | enable (`true`) or disable (`false`) notifications @@ -953,9 +979,11 @@ namespace Example Object result = apiInstance.PrivateToggleNotificationsFromSubaccountGet(sid, state); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling AccountManagementApi.PrivateToggleNotificationsFromSubaccountGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -998,7 +1026,6 @@ Enable or disable login for a subaccount. If login is disabled and a session for ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1008,13 +1035,14 @@ namespace Example { public class PrivateToggleSubaccountLoginGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new AccountManagementApi(); + var apiInstance = new AccountManagementApi(Configuration.Default); var sid = 56; // int? | The user id for the subaccount var state = state_example; // string | enable or disable login. @@ -1024,9 +1052,11 @@ namespace Example Object result = apiInstance.PrivateToggleSubaccountLoginGet(sid, state); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling AccountManagementApi.PrivateToggleSubaccountLoginGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1069,7 +1099,6 @@ Retrieves announcements from the last 30 days. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1079,13 +1108,14 @@ namespace Example { public class PublicGetAnnouncementsGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new AccountManagementApi(); + var apiInstance = new AccountManagementApi(Configuration.Default); try { @@ -1093,9 +1123,11 @@ namespace Example Object result = apiInstance.PublicGetAnnouncementsGet(); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling AccountManagementApi.PublicGetAnnouncementsGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } diff --git a/csharp/docs/AuthenticationApi.md b/csharp/docs/AuthenticationApi.md index e593849..87625b4 100644 --- a/csharp/docs/AuthenticationApi.md +++ b/csharp/docs/AuthenticationApi.md @@ -19,7 +19,6 @@ Retrieve an Oauth access token, to be used for authentication of 'private' reque ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -29,13 +28,14 @@ namespace Example { public class PublicAuthGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new AuthenticationApi(); + var apiInstance = new AuthenticationApi(Configuration.Default); var grantType = grantType_example; // string | Method of authentication var username = your_email@mail.com; // string | Required for grant type `password` var password = your_password; // string | Required for grant type `password` @@ -54,9 +54,11 @@ namespace Example Object result = apiInstance.PublicAuthGet(grantType, username, password, clientId, clientSecret, refreshToken, timestamp, signature, nonce, state, scope); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling AuthenticationApi.PublicAuthGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } diff --git a/csharp/docs/InternalApi.md b/csharp/docs/InternalApi.md index 34d5ea8..65cca33 100644 --- a/csharp/docs/InternalApi.md +++ b/csharp/docs/InternalApi.md @@ -26,7 +26,6 @@ Adds new entry to address book of given type ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -36,13 +35,14 @@ namespace Example { public class PrivateAddToAddressBookGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new InternalApi(); + var apiInstance = new InternalApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var type = type_example; // string | Address book type var address = address_example; // string | Address in currency format, it must be in address book @@ -55,9 +55,11 @@ namespace Example Object result = apiInstance.PrivateAddToAddressBookGet(currency, type, address, name, tfa); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling InternalApi.PrivateAddToAddressBookGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -103,7 +105,6 @@ Disables TFA with one time recovery code ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -113,13 +114,14 @@ namespace Example { public class PrivateDisableTfaWithRecoveryCodeGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new InternalApi(); + var apiInstance = new InternalApi(Configuration.Default); var password = password_example; // string | The password for the subaccount var code = code_example; // string | One time recovery code @@ -129,9 +131,11 @@ namespace Example Object result = apiInstance.PrivateDisableTfaWithRecoveryCodeGet(password, code); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling InternalApi.PrivateDisableTfaWithRecoveryCodeGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -174,7 +178,6 @@ Retrieves address book of given type ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -184,13 +187,14 @@ namespace Example { public class PrivateGetAddressBookGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new InternalApi(); + var apiInstance = new InternalApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var type = type_example; // string | Address book type @@ -200,9 +204,11 @@ namespace Example Object result = apiInstance.PrivateGetAddressBookGet(currency, type); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling InternalApi.PrivateGetAddressBookGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -245,7 +251,6 @@ Adds new entry to address book of given type ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -255,13 +260,14 @@ namespace Example { public class PrivateRemoveFromAddressBookGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new InternalApi(); + var apiInstance = new InternalApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var type = type_example; // string | Address book type var address = address_example; // string | Address in currency format, it must be in address book @@ -273,9 +279,11 @@ namespace Example Object result = apiInstance.PrivateRemoveFromAddressBookGet(currency, type, address, tfa); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling InternalApi.PrivateRemoveFromAddressBookGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -320,7 +328,6 @@ Transfer funds to a subaccount. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -330,13 +337,14 @@ namespace Example { public class PrivateSubmitTransferToSubaccountGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new InternalApi(); + var apiInstance = new InternalApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var amount = 8.14; // decimal? | Amount of funds to be transferred var destination = 1; // int? | Id of destination subaccount @@ -347,9 +355,11 @@ namespace Example Object result = apiInstance.PrivateSubmitTransferToSubaccountGet(currency, amount, destination); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling InternalApi.PrivateSubmitTransferToSubaccountGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -393,7 +403,6 @@ Transfer funds to a another user. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -403,13 +412,14 @@ namespace Example { public class PrivateSubmitTransferToUserGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new InternalApi(); + var apiInstance = new InternalApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var amount = 8.14; // decimal? | Amount of funds to be transferred var destination = destination_example; // string | Destination address from address book @@ -421,9 +431,11 @@ namespace Example Object result = apiInstance.PrivateSubmitTransferToUserGet(currency, amount, destination, tfa); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling InternalApi.PrivateSubmitTransferToUserGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -468,7 +480,6 @@ Enable or disable deposit address creation ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -478,13 +489,14 @@ namespace Example { public class PrivateToggleDepositAddressCreationGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new InternalApi(); + var apiInstance = new InternalApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var state = true; // bool? | @@ -494,9 +506,11 @@ namespace Example Object result = apiInstance.PrivateToggleDepositAddressCreationGet(currency, state); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling InternalApi.PrivateToggleDepositAddressCreationGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -539,7 +553,6 @@ Get information to be displayed in the footer of the website. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -549,13 +562,14 @@ namespace Example { public class PublicGetFooterGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new InternalApi(); + var apiInstance = new InternalApi(Configuration.Default); try { @@ -563,9 +577,11 @@ namespace Example Object result = apiInstance.PublicGetFooterGet(); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling InternalApi.PublicGetFooterGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -604,7 +620,6 @@ Retrives market prices and its implied volatility of options instruments ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -614,13 +629,14 @@ namespace Example { public class PublicGetOptionMarkPricesGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new InternalApi(); + var apiInstance = new InternalApi(Configuration.Default); var currency = currency_example; // string | The currency symbol try @@ -629,9 +645,11 @@ namespace Example Object result = apiInstance.PublicGetOptionMarkPricesGet(currency); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling InternalApi.PublicGetOptionMarkPricesGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -673,7 +691,6 @@ Method used to introduce the client software connected to Deribit platform over ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -683,13 +700,14 @@ namespace Example { public class PublicValidateFieldGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new InternalApi(); + var apiInstance = new InternalApi(Configuration.Default); var field = field_example; // string | Name of the field to be validated, examples: postal_code, date_of_birth var value = value_example; // string | Value to be checked var value2 = value2_example; // string | Additional value to be compared with (optional) @@ -700,9 +718,11 @@ namespace Example Object result = apiInstance.PublicValidateFieldGet(field, value, value2); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling InternalApi.PublicValidateFieldGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } diff --git a/csharp/docs/MarketDataApi.md b/csharp/docs/MarketDataApi.md index c2536a5..2c80b8d 100644 --- a/csharp/docs/MarketDataApi.md +++ b/csharp/docs/MarketDataApi.md @@ -34,7 +34,6 @@ Retrieves the summary information such as open interest, 24h volume, etc. for al ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -44,13 +43,14 @@ namespace Example { public class PublicGetBookSummaryByCurrencyGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new MarketDataApi(); + var apiInstance = new MarketDataApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var kind = kind_example; // string | Instrument kind, if not provided instruments of all kinds are considered (optional) @@ -60,9 +60,11 @@ namespace Example Object result = apiInstance.PublicGetBookSummaryByCurrencyGet(currency, kind); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling MarketDataApi.PublicGetBookSummaryByCurrencyGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -105,7 +107,6 @@ Retrieves the summary information such as open interest, 24h volume, etc. for a ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -115,13 +116,14 @@ namespace Example { public class PublicGetBookSummaryByInstrumentGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new MarketDataApi(); + var apiInstance = new MarketDataApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name try @@ -130,9 +132,11 @@ namespace Example Object result = apiInstance.PublicGetBookSummaryByInstrumentGet(instrumentName); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling MarketDataApi.PublicGetBookSummaryByInstrumentGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -174,7 +178,6 @@ Retrieves contract size of provided instrument. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -184,13 +187,14 @@ namespace Example { public class PublicGetContractSizeGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new MarketDataApi(); + var apiInstance = new MarketDataApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name try @@ -199,9 +203,11 @@ namespace Example Object result = apiInstance.PublicGetContractSizeGet(instrumentName); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling MarketDataApi.PublicGetContractSizeGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -243,7 +249,6 @@ Retrieves all cryptocurrencies supported by the API. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -253,13 +258,14 @@ namespace Example { public class PublicGetCurrenciesGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new MarketDataApi(); + var apiInstance = new MarketDataApi(Configuration.Default); try { @@ -267,9 +273,11 @@ namespace Example Object result = apiInstance.PublicGetCurrenciesGet(); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling MarketDataApi.PublicGetCurrenciesGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -308,7 +316,6 @@ Retrieve the latest user trades that have occurred for PERPETUAL instruments in ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -318,13 +325,14 @@ namespace Example { public class PublicGetFundingChartDataGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new MarketDataApi(); + var apiInstance = new MarketDataApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var length = length_example; // string | Specifies time period. `8h` - 8 hours, `24h` - 24 hours (optional) @@ -334,9 +342,11 @@ namespace Example Object result = apiInstance.PublicGetFundingChartDataGet(instrumentName, length); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling MarketDataApi.PublicGetFundingChartDataGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -379,7 +389,6 @@ Provides information about historical volatility for given cryptocurrency. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -389,13 +398,14 @@ namespace Example { public class PublicGetHistoricalVolatilityGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new MarketDataApi(); + var apiInstance = new MarketDataApi(Configuration.Default); var currency = currency_example; // string | The currency symbol try @@ -404,9 +414,11 @@ namespace Example Object result = apiInstance.PublicGetHistoricalVolatilityGet(currency); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling MarketDataApi.PublicGetHistoricalVolatilityGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -448,7 +460,6 @@ Retrieves the current index price for the instruments, for the selected currency ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -458,13 +469,14 @@ namespace Example { public class PublicGetIndexGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new MarketDataApi(); + var apiInstance = new MarketDataApi(Configuration.Default); var currency = currency_example; // string | The currency symbol try @@ -473,9 +485,11 @@ namespace Example Object result = apiInstance.PublicGetIndexGet(currency); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling MarketDataApi.PublicGetIndexGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -517,7 +531,6 @@ Retrieves available trading instruments. This method can be used to see which in ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -527,13 +540,14 @@ namespace Example { public class PublicGetInstrumentsGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new MarketDataApi(); + var apiInstance = new MarketDataApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var kind = kind_example; // string | Instrument kind, if not provided instruments of all kinds are considered (optional) var expired = true; // bool? | Set to true to show expired instruments instead of active ones. (optional) (default to false) @@ -544,9 +558,11 @@ namespace Example Object result = apiInstance.PublicGetInstrumentsGet(currency, kind, expired); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling MarketDataApi.PublicGetInstrumentsGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -590,7 +606,6 @@ Retrieves historical settlement, delivery and bankruptcy events coming from all ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -600,13 +615,14 @@ namespace Example { public class PublicGetLastSettlementsByCurrencyGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new MarketDataApi(); + var apiInstance = new MarketDataApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var type = type_example; // string | Settlement type (optional) var count = 56; // int? | Number of requested items, default - `20` (optional) @@ -619,9 +635,11 @@ namespace Example Object result = apiInstance.PublicGetLastSettlementsByCurrencyGet(currency, type, count, continuation, searchStartTimestamp); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling MarketDataApi.PublicGetLastSettlementsByCurrencyGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -667,7 +685,6 @@ Retrieves historical public settlement, delivery and bankruptcy events filtered ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -677,13 +694,14 @@ namespace Example { public class PublicGetLastSettlementsByInstrumentGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new MarketDataApi(); + var apiInstance = new MarketDataApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var type = type_example; // string | Settlement type (optional) var count = 56; // int? | Number of requested items, default - `20` (optional) @@ -696,9 +714,11 @@ namespace Example Object result = apiInstance.PublicGetLastSettlementsByInstrumentGet(instrumentName, type, count, continuation, searchStartTimestamp); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling MarketDataApi.PublicGetLastSettlementsByInstrumentGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -744,7 +764,6 @@ Retrieve the latest trades that have occurred for instruments in a specific curr ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -754,13 +773,14 @@ namespace Example { public class PublicGetLastTradesByCurrencyAndTimeGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new MarketDataApi(); + var apiInstance = new MarketDataApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var startTimestamp = 1536569522277; // int? | The earliest timestamp to return result for var endTimestamp = 1536569522277; // int? | The most recent timestamp to return result for @@ -775,9 +795,11 @@ namespace Example Object result = apiInstance.PublicGetLastTradesByCurrencyAndTimeGet(currency, startTimestamp, endTimestamp, kind, count, includeOld, sorting); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling MarketDataApi.PublicGetLastTradesByCurrencyAndTimeGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -825,7 +847,6 @@ Retrieve the latest trades that have occurred for instruments in a specific curr ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -835,13 +856,14 @@ namespace Example { public class PublicGetLastTradesByCurrencyGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new MarketDataApi(); + var apiInstance = new MarketDataApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var kind = kind_example; // string | Instrument kind, if not provided instruments of all kinds are considered (optional) var startId = startId_example; // string | The ID number of the first trade to be returned (optional) @@ -856,9 +878,11 @@ namespace Example Object result = apiInstance.PublicGetLastTradesByCurrencyGet(currency, kind, startId, endId, count, includeOld, sorting); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling MarketDataApi.PublicGetLastTradesByCurrencyGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -906,7 +930,6 @@ Retrieve the latest trades that have occurred for a specific instrument and with ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -916,13 +939,14 @@ namespace Example { public class PublicGetLastTradesByInstrumentAndTimeGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new MarketDataApi(); + var apiInstance = new MarketDataApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var startTimestamp = 1536569522277; // int? | The earliest timestamp to return result for var endTimestamp = 1536569522277; // int? | The most recent timestamp to return result for @@ -936,9 +960,11 @@ namespace Example Object result = apiInstance.PublicGetLastTradesByInstrumentAndTimeGet(instrumentName, startTimestamp, endTimestamp, count, includeOld, sorting); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling MarketDataApi.PublicGetLastTradesByInstrumentAndTimeGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -985,7 +1011,6 @@ Retrieve the latest trades that have occurred for a specific instrument. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -995,13 +1020,14 @@ namespace Example { public class PublicGetLastTradesByInstrumentGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new MarketDataApi(); + var apiInstance = new MarketDataApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var startSeq = 56; // int? | The sequence number of the first trade to be returned (optional) var endSeq = 56; // int? | The sequence number of the last trade to be returned (optional) @@ -1015,9 +1041,11 @@ namespace Example Object result = apiInstance.PublicGetLastTradesByInstrumentGet(instrumentName, startSeq, endSeq, count, includeOld, sorting); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling MarketDataApi.PublicGetLastTradesByInstrumentGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1064,7 +1092,6 @@ Retrieves the order book, along with other market values for a given instrument. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1074,13 +1101,14 @@ namespace Example { public class PublicGetOrderBookGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new MarketDataApi(); + var apiInstance = new MarketDataApi(Configuration.Default); var instrumentName = instrumentName_example; // string | The instrument name for which to retrieve the order book, see [`getinstruments`](#getinstruments) to obtain instrument names. var depth = 8.14; // decimal? | The number of entries to return for bids and asks. (optional) @@ -1090,9 +1118,11 @@ namespace Example Object result = apiInstance.PublicGetOrderBookGet(instrumentName, depth); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling MarketDataApi.PublicGetOrderBookGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1135,7 +1165,6 @@ Retrieves aggregated 24h trade volumes for different instrument types and curren ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1145,13 +1174,14 @@ namespace Example { public class PublicGetTradeVolumesGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new MarketDataApi(); + var apiInstance = new MarketDataApi(Configuration.Default); try { @@ -1159,9 +1189,11 @@ namespace Example Object result = apiInstance.PublicGetTradeVolumesGet(); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling MarketDataApi.PublicGetTradeVolumesGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1200,7 +1232,6 @@ Publicly available market data used to generate a TradingView candle chart. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1210,13 +1241,14 @@ namespace Example { public class PublicGetTradingviewChartDataGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new MarketDataApi(); + var apiInstance = new MarketDataApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var startTimestamp = 1536569522277; // int? | The earliest timestamp to return result for var endTimestamp = 1536569522277; // int? | The most recent timestamp to return result for @@ -1227,9 +1259,11 @@ namespace Example Object result = apiInstance.PublicGetTradingviewChartDataGet(instrumentName, startTimestamp, endTimestamp); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling MarketDataApi.PublicGetTradingviewChartDataGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1273,7 +1307,6 @@ Get ticker for an instrument. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1283,13 +1316,14 @@ namespace Example { public class PublicTickerGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new MarketDataApi(); + var apiInstance = new MarketDataApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name try @@ -1298,9 +1332,11 @@ namespace Example Object result = apiInstance.PublicTickerGet(instrumentName); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling MarketDataApi.PublicTickerGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } diff --git a/csharp/docs/PrivateApi.md b/csharp/docs/PrivateApi.md index 6540d2e..5d5bec9 100644 --- a/csharp/docs/PrivateApi.md +++ b/csharp/docs/PrivateApi.md @@ -68,7 +68,6 @@ Adds new entry to address book of given type ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -78,13 +77,14 @@ namespace Example { public class PrivateAddToAddressBookGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var type = type_example; // string | Address book type var address = address_example; // string | Address in currency format, it must be in address book @@ -97,9 +97,11 @@ namespace Example Object result = apiInstance.PrivateAddToAddressBookGet(currency, type, address, name, tfa); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateAddToAddressBookGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -145,7 +147,6 @@ Places a buy order for an instrument. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -155,13 +156,14 @@ namespace Example { public class PrivateBuyGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var amount = 8.14; // decimal? | It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH var type = type_example; // string | The order type, default: `\"limit\"` (optional) @@ -181,9 +183,11 @@ namespace Example Object result = apiInstance.PrivateBuyGet(instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateBuyGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -236,7 +240,6 @@ Cancels all orders by currency, optionally filtered by instrument kind and/or or ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -246,13 +249,14 @@ namespace Example { public class PrivateCancelAllByCurrencyGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var kind = kind_example; // string | Instrument kind, if not provided instruments of all kinds are considered (optional) var type = type_example; // string | Order type - limit, stop or all, default - `all` (optional) @@ -263,9 +267,11 @@ namespace Example Object result = apiInstance.PrivateCancelAllByCurrencyGet(currency, kind, type); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateCancelAllByCurrencyGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -309,7 +315,6 @@ Cancels all orders by instrument, optionally filtered by order type. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -319,13 +324,14 @@ namespace Example { public class PrivateCancelAllByInstrumentGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var type = type_example; // string | Order type - limit, stop or all, default - `all` (optional) @@ -335,9 +341,11 @@ namespace Example Object result = apiInstance.PrivateCancelAllByInstrumentGet(instrumentName, type); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateCancelAllByInstrumentGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -380,7 +388,6 @@ This method cancels all users orders and stop orders within all currencies and i ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -390,13 +397,14 @@ namespace Example { public class PrivateCancelAllGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); try { @@ -404,9 +412,11 @@ namespace Example Object result = apiInstance.PrivateCancelAllGet(); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateCancelAllGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -445,7 +455,6 @@ Cancel an order, specified by order id ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -455,13 +464,14 @@ namespace Example { public class PrivateCancelGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var orderId = ETH-100234; // string | The order id try @@ -470,9 +480,11 @@ namespace Example Object result = apiInstance.PrivateCancelGet(orderId); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateCancelGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -514,7 +526,6 @@ Cancel transfer ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -524,13 +535,14 @@ namespace Example { public class PrivateCancelTransferByIdGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var id = 12; // int? | Id of transfer var tfa = tfa_example; // string | TFA code, required when TFA is enabled for current account (optional) @@ -541,9 +553,11 @@ namespace Example Object result = apiInstance.PrivateCancelTransferByIdGet(currency, id, tfa); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateCancelTransferByIdGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -587,7 +601,6 @@ Cancels withdrawal request ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -597,13 +610,14 @@ namespace Example { public class PrivateCancelWithdrawalGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var id = 1; // decimal? | The withdrawal id @@ -613,9 +627,11 @@ namespace Example Object result = apiInstance.PrivateCancelWithdrawalGet(currency, id); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateCancelWithdrawalGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -658,7 +674,6 @@ Change the user name for a subaccount ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -668,13 +683,14 @@ namespace Example { public class PrivateChangeSubaccountNameGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var sid = 56; // int? | The user id for the subaccount var name = newUserName; // string | The new user name @@ -684,9 +700,11 @@ namespace Example Object result = apiInstance.PrivateChangeSubaccountNameGet(sid, name); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateChangeSubaccountNameGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -729,7 +747,6 @@ Makes closing position reduce only order . ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -739,13 +756,14 @@ namespace Example { public class PrivateClosePositionGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var type = type_example; // string | The order type var price = 8.14; // decimal? | Optional price for limit order. (optional) @@ -756,9 +774,11 @@ namespace Example Object result = apiInstance.PrivateClosePositionGet(instrumentName, type, price); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateClosePositionGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -802,7 +822,6 @@ Creates deposit address in currency ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -812,13 +831,14 @@ namespace Example { public class PrivateCreateDepositAddressGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var currency = currency_example; // string | The currency symbol try @@ -827,9 +847,11 @@ namespace Example Object result = apiInstance.PrivateCreateDepositAddressGet(currency); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateCreateDepositAddressGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -871,7 +893,6 @@ Create a new subaccount ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -881,13 +902,14 @@ namespace Example { public class PrivateCreateSubaccountGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); try { @@ -895,9 +917,11 @@ namespace Example Object result = apiInstance.PrivateCreateSubaccountGet(); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateCreateSubaccountGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -936,7 +960,6 @@ Disable two factor authentication for a subaccount. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -946,13 +969,14 @@ namespace Example { public class PrivateDisableTfaForSubaccountGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var sid = 56; // int? | The user id for the subaccount try @@ -961,9 +985,11 @@ namespace Example Object result = apiInstance.PrivateDisableTfaForSubaccountGet(sid); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateDisableTfaForSubaccountGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1005,7 +1031,6 @@ Disables TFA with one time recovery code ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1015,13 +1040,14 @@ namespace Example { public class PrivateDisableTfaWithRecoveryCodeGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var password = password_example; // string | The password for the subaccount var code = code_example; // string | One time recovery code @@ -1031,9 +1057,11 @@ namespace Example Object result = apiInstance.PrivateDisableTfaWithRecoveryCodeGet(password, code); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateDisableTfaWithRecoveryCodeGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1076,7 +1104,6 @@ Change price, amount and/or other properties of an order. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1086,13 +1113,14 @@ namespace Example { public class PrivateEditGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var orderId = ETH-100234; // string | The order id var amount = 8.14; // decimal? | It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH var price = 8.14; // decimal? |

The order price in base currency.

When editing an option order with advanced=usd, the field price should be the option price value in USD.

When editing an option order with advanced=implv, the field price should be a value of implied volatility in percentages. For example, price=100, means implied volatility of 100%

@@ -1106,9 +1134,11 @@ namespace Example Object result = apiInstance.PrivateEditGet(orderId, amount, price, postOnly, advanced, stopPrice); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateEditGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1155,7 +1185,6 @@ Retrieves user account summary. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1165,13 +1194,14 @@ namespace Example { public class PrivateGetAccountSummaryGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var extended = false; // bool? | Include additional fields (optional) @@ -1181,9 +1211,11 @@ namespace Example Object result = apiInstance.PrivateGetAccountSummaryGet(currency, extended); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetAccountSummaryGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1226,7 +1258,6 @@ Retrieves address book of given type ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1236,13 +1267,14 @@ namespace Example { public class PrivateGetAddressBookGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var type = type_example; // string | Address book type @@ -1252,9 +1284,11 @@ namespace Example Object result = apiInstance.PrivateGetAddressBookGet(currency, type); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetAddressBookGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1297,7 +1331,6 @@ Retrieve deposit address for currency ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1307,13 +1340,14 @@ namespace Example { public class PrivateGetCurrentDepositAddressGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var currency = currency_example; // string | The currency symbol try @@ -1322,9 +1356,11 @@ namespace Example Object result = apiInstance.PrivateGetCurrentDepositAddressGet(currency); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetCurrentDepositAddressGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1366,7 +1402,6 @@ Retrieve the latest users deposits ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1376,13 +1411,14 @@ namespace Example { public class PrivateGetDepositsGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var count = 56; // int? | Number of requested items, default - `10` (optional) var offset = 10; // int? | The offset for pagination, default - `0` (optional) @@ -1393,9 +1429,11 @@ namespace Example Object result = apiInstance.PrivateGetDepositsGet(currency, count, offset); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetDepositsGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1439,7 +1477,6 @@ Retrieves the language to be used for emails. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1449,13 +1486,14 @@ namespace Example { public class PrivateGetEmailLanguageGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); try { @@ -1463,9 +1501,11 @@ namespace Example Object result = apiInstance.PrivateGetEmailLanguageGet(); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetEmailLanguageGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1504,7 +1544,6 @@ Get margins for given instrument, amount and price. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1514,13 +1553,14 @@ namespace Example { public class PrivateGetMarginsGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var amount = 1; // decimal? | Amount, integer for future, float for option. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH. var price = 8.14; // decimal? | Price @@ -1531,9 +1571,11 @@ namespace Example Object result = apiInstance.PrivateGetMarginsGet(instrumentName, amount, price); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetMarginsGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1577,7 +1619,6 @@ Retrieves announcements that have not been marked read by the user. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1587,13 +1628,14 @@ namespace Example { public class PrivateGetNewAnnouncementsGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); try { @@ -1601,9 +1643,11 @@ namespace Example Object result = apiInstance.PrivateGetNewAnnouncementsGet(); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetNewAnnouncementsGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1642,7 +1686,6 @@ Retrieves list of user's open orders. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1652,13 +1695,14 @@ namespace Example { public class PrivateGetOpenOrdersByCurrencyGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var kind = kind_example; // string | Instrument kind, if not provided instruments of all kinds are considered (optional) var type = type_example; // string | Order type, default - `all` (optional) @@ -1669,9 +1713,11 @@ namespace Example Object result = apiInstance.PrivateGetOpenOrdersByCurrencyGet(currency, kind, type); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetOpenOrdersByCurrencyGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1715,7 +1761,6 @@ Retrieves list of user's open orders within given Instrument. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1725,13 +1770,14 @@ namespace Example { public class PrivateGetOpenOrdersByInstrumentGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var type = type_example; // string | Order type, default - `all` (optional) @@ -1741,9 +1787,11 @@ namespace Example Object result = apiInstance.PrivateGetOpenOrdersByInstrumentGet(instrumentName, type); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetOpenOrdersByInstrumentGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1786,7 +1834,6 @@ Retrieves history of orders that have been partially or fully filled. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1796,13 +1843,14 @@ namespace Example { public class PrivateGetOrderHistoryByCurrencyGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var kind = kind_example; // string | Instrument kind, if not provided instruments of all kinds are considered (optional) var count = 56; // int? | Number of requested items, default - `20` (optional) @@ -1816,9 +1864,11 @@ namespace Example Object result = apiInstance.PrivateGetOrderHistoryByCurrencyGet(currency, kind, count, offset, includeOld, includeUnfilled); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetOrderHistoryByCurrencyGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1865,7 +1915,6 @@ Retrieves history of orders that have been partially or fully filled. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1875,13 +1924,14 @@ namespace Example { public class PrivateGetOrderHistoryByInstrumentGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var count = 56; // int? | Number of requested items, default - `20` (optional) var offset = 10; // int? | The offset for pagination, default - `0` (optional) @@ -1894,9 +1944,11 @@ namespace Example Object result = apiInstance.PrivateGetOrderHistoryByInstrumentGet(instrumentName, count, offset, includeOld, includeUnfilled); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetOrderHistoryByInstrumentGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1942,7 +1994,6 @@ Retrieves initial margins of given orders ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1952,13 +2003,14 @@ namespace Example { public class PrivateGetOrderMarginByIdsGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var ids = new List(); // List | Ids of orders try @@ -1967,9 +2019,11 @@ namespace Example Object result = apiInstance.PrivateGetOrderMarginByIdsGet(ids); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetOrderMarginByIdsGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -2011,7 +2065,6 @@ Retrieve the current state of an order. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -2021,13 +2074,14 @@ namespace Example { public class PrivateGetOrderStateGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var orderId = ETH-100234; // string | The order id try @@ -2036,9 +2090,11 @@ namespace Example Object result = apiInstance.PrivateGetOrderStateGet(orderId); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetOrderStateGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -2080,7 +2136,6 @@ Retrieve user position. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -2090,13 +2145,14 @@ namespace Example { public class PrivateGetPositionGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name try @@ -2105,9 +2161,11 @@ namespace Example Object result = apiInstance.PrivateGetPositionGet(instrumentName); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetPositionGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -2149,7 +2207,6 @@ Retrieve user positions. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -2159,13 +2216,14 @@ namespace Example { public class PrivateGetPositionsGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var currency = currency_example; // string | var kind = kind_example; // string | Kind filter on positions (optional) @@ -2175,9 +2233,11 @@ namespace Example Object result = apiInstance.PrivateGetPositionsGet(currency, kind); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetPositionsGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -2220,7 +2280,6 @@ Retrieves settlement, delivery and bankruptcy events that have affected your acc ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -2230,13 +2289,14 @@ namespace Example { public class PrivateGetSettlementHistoryByCurrencyGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var type = type_example; // string | Settlement type (optional) var count = 56; // int? | Number of requested items, default - `20` (optional) @@ -2247,9 +2307,11 @@ namespace Example Object result = apiInstance.PrivateGetSettlementHistoryByCurrencyGet(currency, type, count); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetSettlementHistoryByCurrencyGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -2293,7 +2355,6 @@ Retrieves public settlement, delivery and bankruptcy events filtered by instrume ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -2303,13 +2364,14 @@ namespace Example { public class PrivateGetSettlementHistoryByInstrumentGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var type = type_example; // string | Settlement type (optional) var count = 56; // int? | Number of requested items, default - `20` (optional) @@ -2320,9 +2382,11 @@ namespace Example Object result = apiInstance.PrivateGetSettlementHistoryByInstrumentGet(instrumentName, type, count); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetSettlementHistoryByInstrumentGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -2366,7 +2430,6 @@ Get information about subaccounts ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -2376,13 +2439,14 @@ namespace Example { public class PrivateGetSubaccountsGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var withPortfolio = true; // bool? | (optional) try @@ -2391,9 +2455,11 @@ namespace Example Object result = apiInstance.PrivateGetSubaccountsGet(withPortfolio); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetSubaccountsGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -2435,7 +2501,6 @@ Adds new entry to address book of given type ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -2445,13 +2510,14 @@ namespace Example { public class PrivateGetTransfersGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var count = 56; // int? | Number of requested items, default - `10` (optional) var offset = 10; // int? | The offset for pagination, default - `0` (optional) @@ -2462,9 +2528,11 @@ namespace Example Object result = apiInstance.PrivateGetTransfersGet(currency, count, offset); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetTransfersGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -2508,7 +2576,6 @@ Retrieve the latest user trades that have occurred for instruments in a specific ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -2518,13 +2585,14 @@ namespace Example { public class PrivateGetUserTradesByCurrencyAndTimeGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var startTimestamp = 1536569522277; // int? | The earliest timestamp to return result for var endTimestamp = 1536569522277; // int? | The most recent timestamp to return result for @@ -2539,9 +2607,11 @@ namespace Example Object result = apiInstance.PrivateGetUserTradesByCurrencyAndTimeGet(currency, startTimestamp, endTimestamp, kind, count, includeOld, sorting); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetUserTradesByCurrencyAndTimeGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -2589,7 +2659,6 @@ Retrieve the latest user trades that have occurred for instruments in a specific ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -2599,13 +2668,14 @@ namespace Example { public class PrivateGetUserTradesByCurrencyGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var kind = kind_example; // string | Instrument kind, if not provided instruments of all kinds are considered (optional) var startId = startId_example; // string | The ID number of the first trade to be returned (optional) @@ -2620,9 +2690,11 @@ namespace Example Object result = apiInstance.PrivateGetUserTradesByCurrencyGet(currency, kind, startId, endId, count, includeOld, sorting); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetUserTradesByCurrencyGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -2670,7 +2742,6 @@ Retrieve the latest user trades that have occurred for a specific instrument and ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -2680,13 +2751,14 @@ namespace Example { public class PrivateGetUserTradesByInstrumentAndTimeGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var startTimestamp = 1536569522277; // int? | The earliest timestamp to return result for var endTimestamp = 1536569522277; // int? | The most recent timestamp to return result for @@ -2700,9 +2772,11 @@ namespace Example Object result = apiInstance.PrivateGetUserTradesByInstrumentAndTimeGet(instrumentName, startTimestamp, endTimestamp, count, includeOld, sorting); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetUserTradesByInstrumentAndTimeGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -2749,7 +2823,6 @@ Retrieve the latest user trades that have occurred for a specific instrument. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -2759,13 +2832,14 @@ namespace Example { public class PrivateGetUserTradesByInstrumentGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var startSeq = 56; // int? | The sequence number of the first trade to be returned (optional) var endSeq = 56; // int? | The sequence number of the last trade to be returned (optional) @@ -2779,9 +2853,11 @@ namespace Example Object result = apiInstance.PrivateGetUserTradesByInstrumentGet(instrumentName, startSeq, endSeq, count, includeOld, sorting); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetUserTradesByInstrumentGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -2828,7 +2904,6 @@ Retrieve the list of user trades that was created for given order ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -2838,13 +2913,14 @@ namespace Example { public class PrivateGetUserTradesByOrderGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var orderId = ETH-100234; // string | The order id var sorting = sorting_example; // string | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) @@ -2854,9 +2930,11 @@ namespace Example Object result = apiInstance.PrivateGetUserTradesByOrderGet(orderId, sorting); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetUserTradesByOrderGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -2899,7 +2977,6 @@ Retrieve the latest users withdrawals ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -2909,13 +2986,14 @@ namespace Example { public class PrivateGetWithdrawalsGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var count = 56; // int? | Number of requested items, default - `10` (optional) var offset = 10; // int? | The offset for pagination, default - `0` (optional) @@ -2926,9 +3004,11 @@ namespace Example Object result = apiInstance.PrivateGetWithdrawalsGet(currency, count, offset); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateGetWithdrawalsGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -2972,7 +3052,6 @@ Adds new entry to address book of given type ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -2982,13 +3061,14 @@ namespace Example { public class PrivateRemoveFromAddressBookGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var type = type_example; // string | Address book type var address = address_example; // string | Address in currency format, it must be in address book @@ -3000,9 +3080,11 @@ namespace Example Object result = apiInstance.PrivateRemoveFromAddressBookGet(currency, type, address, tfa); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateRemoveFromAddressBookGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -3047,7 +3129,6 @@ Places a sell order for an instrument. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -3057,13 +3138,14 @@ namespace Example { public class PrivateSellGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var amount = 8.14; // decimal? | It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH var type = type_example; // string | The order type, default: `\"limit\"` (optional) @@ -3083,9 +3165,11 @@ namespace Example Object result = apiInstance.PrivateSellGet(instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateSellGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -3138,7 +3222,6 @@ Marks an announcement as read, so it will not be shown in `get_new_announcements ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -3148,13 +3231,14 @@ namespace Example { public class PrivateSetAnnouncementAsReadGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var announcementId = 8.14; // decimal? | the ID of the announcement try @@ -3163,9 +3247,11 @@ namespace Example Object result = apiInstance.PrivateSetAnnouncementAsReadGet(announcementId); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateSetAnnouncementAsReadGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -3207,7 +3293,6 @@ Assign an email address to a subaccount. User will receive an email with confirm ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -3217,13 +3302,14 @@ namespace Example { public class PrivateSetEmailForSubaccountGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var sid = 56; // int? | The user id for the subaccount var email = subaccount_1@email.com; // string | The email address for the subaccount @@ -3233,9 +3319,11 @@ namespace Example Object result = apiInstance.PrivateSetEmailForSubaccountGet(sid, email); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateSetEmailForSubaccountGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -3278,7 +3366,6 @@ Changes the language to be used for emails. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -3288,13 +3375,14 @@ namespace Example { public class PrivateSetEmailLanguageGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var language = en; // string | The abbreviated language name. Valid values include `\"en\"`, `\"ko\"`, `\"zh\"` try @@ -3303,9 +3391,11 @@ namespace Example Object result = apiInstance.PrivateSetEmailLanguageGet(language); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateSetEmailLanguageGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -3347,7 +3437,6 @@ Set the password for the subaccount ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -3357,13 +3446,14 @@ namespace Example { public class PrivateSetPasswordForSubaccountGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var sid = 56; // int? | The user id for the subaccount var password = password_example; // string | The password for the subaccount @@ -3373,9 +3463,11 @@ namespace Example Object result = apiInstance.PrivateSetPasswordForSubaccountGet(sid, password); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateSetPasswordForSubaccountGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -3418,7 +3510,6 @@ Transfer funds to a subaccount. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -3428,13 +3519,14 @@ namespace Example { public class PrivateSubmitTransferToSubaccountGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var amount = 8.14; // decimal? | Amount of funds to be transferred var destination = 1; // int? | Id of destination subaccount @@ -3445,9 +3537,11 @@ namespace Example Object result = apiInstance.PrivateSubmitTransferToSubaccountGet(currency, amount, destination); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateSubmitTransferToSubaccountGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -3491,7 +3585,6 @@ Transfer funds to a another user. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -3501,13 +3594,14 @@ namespace Example { public class PrivateSubmitTransferToUserGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var amount = 8.14; // decimal? | Amount of funds to be transferred var destination = destination_example; // string | Destination address from address book @@ -3519,9 +3613,11 @@ namespace Example Object result = apiInstance.PrivateSubmitTransferToUserGet(currency, amount, destination, tfa); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateSubmitTransferToUserGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -3566,7 +3662,6 @@ Enable or disable deposit address creation ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -3576,13 +3671,14 @@ namespace Example { public class PrivateToggleDepositAddressCreationGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var state = true; // bool? | @@ -3592,9 +3688,11 @@ namespace Example Object result = apiInstance.PrivateToggleDepositAddressCreationGet(currency, state); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateToggleDepositAddressCreationGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -3637,7 +3735,6 @@ Enable or disable sending of notifications for the subaccount. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -3647,13 +3744,14 @@ namespace Example { public class PrivateToggleNotificationsFromSubaccountGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var sid = 56; // int? | The user id for the subaccount var state = true; // bool? | enable (`true`) or disable (`false`) notifications @@ -3663,9 +3761,11 @@ namespace Example Object result = apiInstance.PrivateToggleNotificationsFromSubaccountGet(sid, state); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateToggleNotificationsFromSubaccountGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -3708,7 +3808,6 @@ Enable or disable login for a subaccount. If login is disabled and a session for ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -3718,13 +3817,14 @@ namespace Example { public class PrivateToggleSubaccountLoginGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var sid = 56; // int? | The user id for the subaccount var state = state_example; // string | enable or disable login. @@ -3734,9 +3834,11 @@ namespace Example Object result = apiInstance.PrivateToggleSubaccountLoginGet(sid, state); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateToggleSubaccountLoginGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -3779,7 +3881,6 @@ Creates a new withdrawal request ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -3789,13 +3890,14 @@ namespace Example { public class PrivateWithdrawGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PrivateApi(); + var apiInstance = new PrivateApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var address = address_example; // string | Address in currency format, it must be in address book var amount = 8.14; // decimal? | Amount of funds to be withdrawn @@ -3808,9 +3910,11 @@ namespace Example Object result = apiInstance.PrivateWithdrawGet(currency, address, amount, priority, tfa); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PrivateApi.PrivateWithdrawGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } diff --git a/csharp/docs/PublicApi.md b/csharp/docs/PublicApi.md index b8c1bd8..a3b9170 100644 --- a/csharp/docs/PublicApi.md +++ b/csharp/docs/PublicApi.md @@ -41,7 +41,6 @@ Retrieve an Oauth access token, to be used for authentication of 'private' reque ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -51,13 +50,14 @@ namespace Example { public class PublicAuthGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PublicApi(); + var apiInstance = new PublicApi(Configuration.Default); var grantType = grantType_example; // string | Method of authentication var username = your_email@mail.com; // string | Required for grant type `password` var password = your_password; // string | Required for grant type `password` @@ -76,9 +76,11 @@ namespace Example Object result = apiInstance.PublicAuthGet(grantType, username, password, clientId, clientSecret, refreshToken, timestamp, signature, nonce, state, scope); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PublicApi.PublicAuthGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -130,7 +132,6 @@ Retrieves announcements from the last 30 days. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -140,13 +141,14 @@ namespace Example { public class PublicGetAnnouncementsGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PublicApi(); + var apiInstance = new PublicApi(Configuration.Default); try { @@ -154,9 +156,11 @@ namespace Example Object result = apiInstance.PublicGetAnnouncementsGet(); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PublicApi.PublicGetAnnouncementsGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -195,7 +199,6 @@ Retrieves the summary information such as open interest, 24h volume, etc. for al ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -205,13 +208,14 @@ namespace Example { public class PublicGetBookSummaryByCurrencyGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PublicApi(); + var apiInstance = new PublicApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var kind = kind_example; // string | Instrument kind, if not provided instruments of all kinds are considered (optional) @@ -221,9 +225,11 @@ namespace Example Object result = apiInstance.PublicGetBookSummaryByCurrencyGet(currency, kind); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PublicApi.PublicGetBookSummaryByCurrencyGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -266,7 +272,6 @@ Retrieves the summary information such as open interest, 24h volume, etc. for a ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -276,13 +281,14 @@ namespace Example { public class PublicGetBookSummaryByInstrumentGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PublicApi(); + var apiInstance = new PublicApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name try @@ -291,9 +297,11 @@ namespace Example Object result = apiInstance.PublicGetBookSummaryByInstrumentGet(instrumentName); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PublicApi.PublicGetBookSummaryByInstrumentGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -335,7 +343,6 @@ Retrieves contract size of provided instrument. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -345,13 +352,14 @@ namespace Example { public class PublicGetContractSizeGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PublicApi(); + var apiInstance = new PublicApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name try @@ -360,9 +368,11 @@ namespace Example Object result = apiInstance.PublicGetContractSizeGet(instrumentName); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PublicApi.PublicGetContractSizeGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -404,7 +414,6 @@ Retrieves all cryptocurrencies supported by the API. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -414,13 +423,14 @@ namespace Example { public class PublicGetCurrenciesGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PublicApi(); + var apiInstance = new PublicApi(Configuration.Default); try { @@ -428,9 +438,11 @@ namespace Example Object result = apiInstance.PublicGetCurrenciesGet(); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PublicApi.PublicGetCurrenciesGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -469,7 +481,6 @@ Retrieve the latest user trades that have occurred for PERPETUAL instruments in ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -479,13 +490,14 @@ namespace Example { public class PublicGetFundingChartDataGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PublicApi(); + var apiInstance = new PublicApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var length = length_example; // string | Specifies time period. `8h` - 8 hours, `24h` - 24 hours (optional) @@ -495,9 +507,11 @@ namespace Example Object result = apiInstance.PublicGetFundingChartDataGet(instrumentName, length); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PublicApi.PublicGetFundingChartDataGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -540,7 +554,6 @@ Provides information about historical volatility for given cryptocurrency. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -550,13 +563,14 @@ namespace Example { public class PublicGetHistoricalVolatilityGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PublicApi(); + var apiInstance = new PublicApi(Configuration.Default); var currency = currency_example; // string | The currency symbol try @@ -565,9 +579,11 @@ namespace Example Object result = apiInstance.PublicGetHistoricalVolatilityGet(currency); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PublicApi.PublicGetHistoricalVolatilityGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -609,7 +625,6 @@ Retrieves the current index price for the instruments, for the selected currency ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -619,13 +634,14 @@ namespace Example { public class PublicGetIndexGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PublicApi(); + var apiInstance = new PublicApi(Configuration.Default); var currency = currency_example; // string | The currency symbol try @@ -634,9 +650,11 @@ namespace Example Object result = apiInstance.PublicGetIndexGet(currency); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PublicApi.PublicGetIndexGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -678,7 +696,6 @@ Retrieves available trading instruments. This method can be used to see which in ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -688,13 +705,14 @@ namespace Example { public class PublicGetInstrumentsGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PublicApi(); + var apiInstance = new PublicApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var kind = kind_example; // string | Instrument kind, if not provided instruments of all kinds are considered (optional) var expired = true; // bool? | Set to true to show expired instruments instead of active ones. (optional) (default to false) @@ -705,9 +723,11 @@ namespace Example Object result = apiInstance.PublicGetInstrumentsGet(currency, kind, expired); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PublicApi.PublicGetInstrumentsGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -751,7 +771,6 @@ Retrieves historical settlement, delivery and bankruptcy events coming from all ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -761,13 +780,14 @@ namespace Example { public class PublicGetLastSettlementsByCurrencyGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PublicApi(); + var apiInstance = new PublicApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var type = type_example; // string | Settlement type (optional) var count = 56; // int? | Number of requested items, default - `20` (optional) @@ -780,9 +800,11 @@ namespace Example Object result = apiInstance.PublicGetLastSettlementsByCurrencyGet(currency, type, count, continuation, searchStartTimestamp); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PublicApi.PublicGetLastSettlementsByCurrencyGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -828,7 +850,6 @@ Retrieves historical public settlement, delivery and bankruptcy events filtered ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -838,13 +859,14 @@ namespace Example { public class PublicGetLastSettlementsByInstrumentGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PublicApi(); + var apiInstance = new PublicApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var type = type_example; // string | Settlement type (optional) var count = 56; // int? | Number of requested items, default - `20` (optional) @@ -857,9 +879,11 @@ namespace Example Object result = apiInstance.PublicGetLastSettlementsByInstrumentGet(instrumentName, type, count, continuation, searchStartTimestamp); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PublicApi.PublicGetLastSettlementsByInstrumentGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -905,7 +929,6 @@ Retrieve the latest trades that have occurred for instruments in a specific curr ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -915,13 +938,14 @@ namespace Example { public class PublicGetLastTradesByCurrencyAndTimeGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PublicApi(); + var apiInstance = new PublicApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var startTimestamp = 1536569522277; // int? | The earliest timestamp to return result for var endTimestamp = 1536569522277; // int? | The most recent timestamp to return result for @@ -936,9 +960,11 @@ namespace Example Object result = apiInstance.PublicGetLastTradesByCurrencyAndTimeGet(currency, startTimestamp, endTimestamp, kind, count, includeOld, sorting); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PublicApi.PublicGetLastTradesByCurrencyAndTimeGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -986,7 +1012,6 @@ Retrieve the latest trades that have occurred for instruments in a specific curr ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -996,13 +1021,14 @@ namespace Example { public class PublicGetLastTradesByCurrencyGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PublicApi(); + var apiInstance = new PublicApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var kind = kind_example; // string | Instrument kind, if not provided instruments of all kinds are considered (optional) var startId = startId_example; // string | The ID number of the first trade to be returned (optional) @@ -1017,9 +1043,11 @@ namespace Example Object result = apiInstance.PublicGetLastTradesByCurrencyGet(currency, kind, startId, endId, count, includeOld, sorting); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PublicApi.PublicGetLastTradesByCurrencyGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1067,7 +1095,6 @@ Retrieve the latest trades that have occurred for a specific instrument and with ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1077,13 +1104,14 @@ namespace Example { public class PublicGetLastTradesByInstrumentAndTimeGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PublicApi(); + var apiInstance = new PublicApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var startTimestamp = 1536569522277; // int? | The earliest timestamp to return result for var endTimestamp = 1536569522277; // int? | The most recent timestamp to return result for @@ -1097,9 +1125,11 @@ namespace Example Object result = apiInstance.PublicGetLastTradesByInstrumentAndTimeGet(instrumentName, startTimestamp, endTimestamp, count, includeOld, sorting); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PublicApi.PublicGetLastTradesByInstrumentAndTimeGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1146,7 +1176,6 @@ Retrieve the latest trades that have occurred for a specific instrument. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1156,13 +1185,14 @@ namespace Example { public class PublicGetLastTradesByInstrumentGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PublicApi(); + var apiInstance = new PublicApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var startSeq = 56; // int? | The sequence number of the first trade to be returned (optional) var endSeq = 56; // int? | The sequence number of the last trade to be returned (optional) @@ -1176,9 +1206,11 @@ namespace Example Object result = apiInstance.PublicGetLastTradesByInstrumentGet(instrumentName, startSeq, endSeq, count, includeOld, sorting); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PublicApi.PublicGetLastTradesByInstrumentGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1225,7 +1257,6 @@ Retrieves the order book, along with other market values for a given instrument. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1235,13 +1266,14 @@ namespace Example { public class PublicGetOrderBookGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PublicApi(); + var apiInstance = new PublicApi(Configuration.Default); var instrumentName = instrumentName_example; // string | The instrument name for which to retrieve the order book, see [`getinstruments`](#getinstruments) to obtain instrument names. var depth = 8.14; // decimal? | The number of entries to return for bids and asks. (optional) @@ -1251,9 +1283,11 @@ namespace Example Object result = apiInstance.PublicGetOrderBookGet(instrumentName, depth); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PublicApi.PublicGetOrderBookGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1296,7 +1330,6 @@ Retrieves the current time (in milliseconds). This API endpoint can be used to c ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1306,13 +1339,14 @@ namespace Example { public class PublicGetTimeGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PublicApi(); + var apiInstance = new PublicApi(Configuration.Default); try { @@ -1320,9 +1354,11 @@ namespace Example Object result = apiInstance.PublicGetTimeGet(); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PublicApi.PublicGetTimeGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1361,7 +1397,6 @@ Retrieves aggregated 24h trade volumes for different instrument types and curren ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1371,13 +1406,14 @@ namespace Example { public class PublicGetTradeVolumesGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PublicApi(); + var apiInstance = new PublicApi(Configuration.Default); try { @@ -1385,9 +1421,11 @@ namespace Example Object result = apiInstance.PublicGetTradeVolumesGet(); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PublicApi.PublicGetTradeVolumesGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1426,7 +1464,6 @@ Publicly available market data used to generate a TradingView candle chart. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1436,13 +1473,14 @@ namespace Example { public class PublicGetTradingviewChartDataGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PublicApi(); + var apiInstance = new PublicApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var startTimestamp = 1536569522277; // int? | The earliest timestamp to return result for var endTimestamp = 1536569522277; // int? | The most recent timestamp to return result for @@ -1453,9 +1491,11 @@ namespace Example Object result = apiInstance.PublicGetTradingviewChartDataGet(instrumentName, startTimestamp, endTimestamp); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PublicApi.PublicGetTradingviewChartDataGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1499,7 +1539,6 @@ Tests the connection to the API server, and returns its version. You can use thi ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1509,13 +1548,14 @@ namespace Example { public class PublicTestGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PublicApi(); + var apiInstance = new PublicApi(Configuration.Default); var expectedResult = expectedResult_example; // string | The value \"exception\" will trigger an error response. This may be useful for testing wrapper libraries. (optional) try @@ -1524,9 +1564,11 @@ namespace Example Object result = apiInstance.PublicTestGet(expectedResult); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PublicApi.PublicTestGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1568,7 +1610,6 @@ Get ticker for an instrument. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1578,13 +1619,14 @@ namespace Example { public class PublicTickerGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PublicApi(); + var apiInstance = new PublicApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name try @@ -1593,9 +1635,11 @@ namespace Example Object result = apiInstance.PublicTickerGet(instrumentName); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PublicApi.PublicTickerGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1637,7 +1681,6 @@ Method used to introduce the client software connected to Deribit platform over ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1647,13 +1690,14 @@ namespace Example { public class PublicValidateFieldGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new PublicApi(); + var apiInstance = new PublicApi(Configuration.Default); var field = field_example; // string | Name of the field to be validated, examples: postal_code, date_of_birth var value = value_example; // string | Value to be checked var value2 = value2_example; // string | Additional value to be compared with (optional) @@ -1664,9 +1708,11 @@ namespace Example Object result = apiInstance.PublicValidateFieldGet(field, value, value2); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling PublicApi.PublicValidateFieldGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } diff --git a/csharp/docs/SupportingApi.md b/csharp/docs/SupportingApi.md index 55d70c5..1b61b6a 100644 --- a/csharp/docs/SupportingApi.md +++ b/csharp/docs/SupportingApi.md @@ -18,7 +18,6 @@ Retrieves the current time (in milliseconds). This API endpoint can be used to c ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -28,13 +27,14 @@ namespace Example { public class PublicGetTimeGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new SupportingApi(); + var apiInstance = new SupportingApi(Configuration.Default); try { @@ -42,9 +42,11 @@ namespace Example Object result = apiInstance.PublicGetTimeGet(); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling SupportingApi.PublicGetTimeGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -83,7 +85,6 @@ Tests the connection to the API server, and returns its version. You can use thi ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -93,13 +94,14 @@ namespace Example { public class PublicTestGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new SupportingApi(); + var apiInstance = new SupportingApi(Configuration.Default); var expectedResult = expectedResult_example; // string | The value \"exception\" will trigger an error response. This may be useful for testing wrapper libraries. (optional) try @@ -108,9 +110,11 @@ namespace Example Object result = apiInstance.PublicTestGet(expectedResult); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling SupportingApi.PublicTestGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } diff --git a/csharp/docs/TradingApi.md b/csharp/docs/TradingApi.md index 8e33652..0a54c56 100644 --- a/csharp/docs/TradingApi.md +++ b/csharp/docs/TradingApi.md @@ -38,7 +38,6 @@ Places a buy order for an instrument. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -48,13 +47,14 @@ namespace Example { public class PrivateBuyGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new TradingApi(); + var apiInstance = new TradingApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var amount = 8.14; // decimal? | It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH var type = type_example; // string | The order type, default: `\"limit\"` (optional) @@ -74,9 +74,11 @@ namespace Example Object result = apiInstance.PrivateBuyGet(instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling TradingApi.PrivateBuyGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -129,7 +131,6 @@ Cancels all orders by currency, optionally filtered by instrument kind and/or or ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -139,13 +140,14 @@ namespace Example { public class PrivateCancelAllByCurrencyGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new TradingApi(); + var apiInstance = new TradingApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var kind = kind_example; // string | Instrument kind, if not provided instruments of all kinds are considered (optional) var type = type_example; // string | Order type - limit, stop or all, default - `all` (optional) @@ -156,9 +158,11 @@ namespace Example Object result = apiInstance.PrivateCancelAllByCurrencyGet(currency, kind, type); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling TradingApi.PrivateCancelAllByCurrencyGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -202,7 +206,6 @@ Cancels all orders by instrument, optionally filtered by order type. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -212,13 +215,14 @@ namespace Example { public class PrivateCancelAllByInstrumentGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new TradingApi(); + var apiInstance = new TradingApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var type = type_example; // string | Order type - limit, stop or all, default - `all` (optional) @@ -228,9 +232,11 @@ namespace Example Object result = apiInstance.PrivateCancelAllByInstrumentGet(instrumentName, type); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling TradingApi.PrivateCancelAllByInstrumentGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -273,7 +279,6 @@ This method cancels all users orders and stop orders within all currencies and i ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -283,13 +288,14 @@ namespace Example { public class PrivateCancelAllGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new TradingApi(); + var apiInstance = new TradingApi(Configuration.Default); try { @@ -297,9 +303,11 @@ namespace Example Object result = apiInstance.PrivateCancelAllGet(); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling TradingApi.PrivateCancelAllGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -338,7 +346,6 @@ Cancel an order, specified by order id ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -348,13 +355,14 @@ namespace Example { public class PrivateCancelGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new TradingApi(); + var apiInstance = new TradingApi(Configuration.Default); var orderId = ETH-100234; // string | The order id try @@ -363,9 +371,11 @@ namespace Example Object result = apiInstance.PrivateCancelGet(orderId); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling TradingApi.PrivateCancelGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -407,7 +417,6 @@ Makes closing position reduce only order . ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -417,13 +426,14 @@ namespace Example { public class PrivateClosePositionGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new TradingApi(); + var apiInstance = new TradingApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var type = type_example; // string | The order type var price = 8.14; // decimal? | Optional price for limit order. (optional) @@ -434,9 +444,11 @@ namespace Example Object result = apiInstance.PrivateClosePositionGet(instrumentName, type, price); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling TradingApi.PrivateClosePositionGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -480,7 +492,6 @@ Change price, amount and/or other properties of an order. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -490,13 +501,14 @@ namespace Example { public class PrivateEditGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new TradingApi(); + var apiInstance = new TradingApi(Configuration.Default); var orderId = ETH-100234; // string | The order id var amount = 8.14; // decimal? | It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH var price = 8.14; // decimal? |

The order price in base currency.

When editing an option order with advanced=usd, the field price should be the option price value in USD.

When editing an option order with advanced=implv, the field price should be a value of implied volatility in percentages. For example, price=100, means implied volatility of 100%

@@ -510,9 +522,11 @@ namespace Example Object result = apiInstance.PrivateEditGet(orderId, amount, price, postOnly, advanced, stopPrice); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling TradingApi.PrivateEditGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -559,7 +573,6 @@ Get margins for given instrument, amount and price. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -569,13 +582,14 @@ namespace Example { public class PrivateGetMarginsGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new TradingApi(); + var apiInstance = new TradingApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var amount = 1; // decimal? | Amount, integer for future, float for option. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH. var price = 8.14; // decimal? | Price @@ -586,9 +600,11 @@ namespace Example Object result = apiInstance.PrivateGetMarginsGet(instrumentName, amount, price); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling TradingApi.PrivateGetMarginsGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -632,7 +648,6 @@ Retrieves list of user's open orders. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -642,13 +657,14 @@ namespace Example { public class PrivateGetOpenOrdersByCurrencyGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new TradingApi(); + var apiInstance = new TradingApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var kind = kind_example; // string | Instrument kind, if not provided instruments of all kinds are considered (optional) var type = type_example; // string | Order type, default - `all` (optional) @@ -659,9 +675,11 @@ namespace Example Object result = apiInstance.PrivateGetOpenOrdersByCurrencyGet(currency, kind, type); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling TradingApi.PrivateGetOpenOrdersByCurrencyGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -705,7 +723,6 @@ Retrieves list of user's open orders within given Instrument. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -715,13 +732,14 @@ namespace Example { public class PrivateGetOpenOrdersByInstrumentGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new TradingApi(); + var apiInstance = new TradingApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var type = type_example; // string | Order type, default - `all` (optional) @@ -731,9 +749,11 @@ namespace Example Object result = apiInstance.PrivateGetOpenOrdersByInstrumentGet(instrumentName, type); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling TradingApi.PrivateGetOpenOrdersByInstrumentGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -776,7 +796,6 @@ Retrieves history of orders that have been partially or fully filled. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -786,13 +805,14 @@ namespace Example { public class PrivateGetOrderHistoryByCurrencyGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new TradingApi(); + var apiInstance = new TradingApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var kind = kind_example; // string | Instrument kind, if not provided instruments of all kinds are considered (optional) var count = 56; // int? | Number of requested items, default - `20` (optional) @@ -806,9 +826,11 @@ namespace Example Object result = apiInstance.PrivateGetOrderHistoryByCurrencyGet(currency, kind, count, offset, includeOld, includeUnfilled); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling TradingApi.PrivateGetOrderHistoryByCurrencyGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -855,7 +877,6 @@ Retrieves history of orders that have been partially or fully filled. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -865,13 +886,14 @@ namespace Example { public class PrivateGetOrderHistoryByInstrumentGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new TradingApi(); + var apiInstance = new TradingApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var count = 56; // int? | Number of requested items, default - `20` (optional) var offset = 10; // int? | The offset for pagination, default - `0` (optional) @@ -884,9 +906,11 @@ namespace Example Object result = apiInstance.PrivateGetOrderHistoryByInstrumentGet(instrumentName, count, offset, includeOld, includeUnfilled); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling TradingApi.PrivateGetOrderHistoryByInstrumentGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -932,7 +956,6 @@ Retrieves initial margins of given orders ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -942,13 +965,14 @@ namespace Example { public class PrivateGetOrderMarginByIdsGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new TradingApi(); + var apiInstance = new TradingApi(Configuration.Default); var ids = new List(); // List | Ids of orders try @@ -957,9 +981,11 @@ namespace Example Object result = apiInstance.PrivateGetOrderMarginByIdsGet(ids); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling TradingApi.PrivateGetOrderMarginByIdsGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1001,7 +1027,6 @@ Retrieve the current state of an order. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1011,13 +1036,14 @@ namespace Example { public class PrivateGetOrderStateGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new TradingApi(); + var apiInstance = new TradingApi(Configuration.Default); var orderId = ETH-100234; // string | The order id try @@ -1026,9 +1052,11 @@ namespace Example Object result = apiInstance.PrivateGetOrderStateGet(orderId); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling TradingApi.PrivateGetOrderStateGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1070,7 +1098,6 @@ Retrieves settlement, delivery and bankruptcy events that have affected your acc ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1080,13 +1107,14 @@ namespace Example { public class PrivateGetSettlementHistoryByCurrencyGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new TradingApi(); + var apiInstance = new TradingApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var type = type_example; // string | Settlement type (optional) var count = 56; // int? | Number of requested items, default - `20` (optional) @@ -1097,9 +1125,11 @@ namespace Example Object result = apiInstance.PrivateGetSettlementHistoryByCurrencyGet(currency, type, count); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling TradingApi.PrivateGetSettlementHistoryByCurrencyGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1143,7 +1173,6 @@ Retrieves public settlement, delivery and bankruptcy events filtered by instrume ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1153,13 +1182,14 @@ namespace Example { public class PrivateGetSettlementHistoryByInstrumentGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new TradingApi(); + var apiInstance = new TradingApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var type = type_example; // string | Settlement type (optional) var count = 56; // int? | Number of requested items, default - `20` (optional) @@ -1170,9 +1200,11 @@ namespace Example Object result = apiInstance.PrivateGetSettlementHistoryByInstrumentGet(instrumentName, type, count); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling TradingApi.PrivateGetSettlementHistoryByInstrumentGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1216,7 +1248,6 @@ Retrieve the latest user trades that have occurred for instruments in a specific ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1226,13 +1257,14 @@ namespace Example { public class PrivateGetUserTradesByCurrencyAndTimeGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new TradingApi(); + var apiInstance = new TradingApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var startTimestamp = 1536569522277; // int? | The earliest timestamp to return result for var endTimestamp = 1536569522277; // int? | The most recent timestamp to return result for @@ -1247,9 +1279,11 @@ namespace Example Object result = apiInstance.PrivateGetUserTradesByCurrencyAndTimeGet(currency, startTimestamp, endTimestamp, kind, count, includeOld, sorting); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling TradingApi.PrivateGetUserTradesByCurrencyAndTimeGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1297,7 +1331,6 @@ Retrieve the latest user trades that have occurred for instruments in a specific ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1307,13 +1340,14 @@ namespace Example { public class PrivateGetUserTradesByCurrencyGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new TradingApi(); + var apiInstance = new TradingApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var kind = kind_example; // string | Instrument kind, if not provided instruments of all kinds are considered (optional) var startId = startId_example; // string | The ID number of the first trade to be returned (optional) @@ -1328,9 +1362,11 @@ namespace Example Object result = apiInstance.PrivateGetUserTradesByCurrencyGet(currency, kind, startId, endId, count, includeOld, sorting); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling TradingApi.PrivateGetUserTradesByCurrencyGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1378,7 +1414,6 @@ Retrieve the latest user trades that have occurred for a specific instrument and ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1388,13 +1423,14 @@ namespace Example { public class PrivateGetUserTradesByInstrumentAndTimeGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new TradingApi(); + var apiInstance = new TradingApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var startTimestamp = 1536569522277; // int? | The earliest timestamp to return result for var endTimestamp = 1536569522277; // int? | The most recent timestamp to return result for @@ -1408,9 +1444,11 @@ namespace Example Object result = apiInstance.PrivateGetUserTradesByInstrumentAndTimeGet(instrumentName, startTimestamp, endTimestamp, count, includeOld, sorting); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling TradingApi.PrivateGetUserTradesByInstrumentAndTimeGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1457,7 +1495,6 @@ Retrieve the latest user trades that have occurred for a specific instrument. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1467,13 +1504,14 @@ namespace Example { public class PrivateGetUserTradesByInstrumentGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new TradingApi(); + var apiInstance = new TradingApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var startSeq = 56; // int? | The sequence number of the first trade to be returned (optional) var endSeq = 56; // int? | The sequence number of the last trade to be returned (optional) @@ -1487,9 +1525,11 @@ namespace Example Object result = apiInstance.PrivateGetUserTradesByInstrumentGet(instrumentName, startSeq, endSeq, count, includeOld, sorting); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling TradingApi.PrivateGetUserTradesByInstrumentGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1536,7 +1576,6 @@ Retrieve the list of user trades that was created for given order ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1546,13 +1585,14 @@ namespace Example { public class PrivateGetUserTradesByOrderGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new TradingApi(); + var apiInstance = new TradingApi(Configuration.Default); var orderId = ETH-100234; // string | The order id var sorting = sorting_example; // string | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) @@ -1562,9 +1602,11 @@ namespace Example Object result = apiInstance.PrivateGetUserTradesByOrderGet(orderId, sorting); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling TradingApi.PrivateGetUserTradesByOrderGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -1607,7 +1649,6 @@ Places a sell order for an instrument. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -1617,13 +1658,14 @@ namespace Example { public class PrivateSellGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new TradingApi(); + var apiInstance = new TradingApi(Configuration.Default); var instrumentName = BTC-PERPETUAL; // string | Instrument name var amount = 8.14; // decimal? | It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH var type = type_example; // string | The order type, default: `\"limit\"` (optional) @@ -1643,9 +1685,11 @@ namespace Example Object result = apiInstance.PrivateSellGet(instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling TradingApi.PrivateSellGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } diff --git a/csharp/docs/WalletApi.md b/csharp/docs/WalletApi.md index 95b9599..cd15118 100644 --- a/csharp/docs/WalletApi.md +++ b/csharp/docs/WalletApi.md @@ -30,7 +30,6 @@ Adds new entry to address book of given type ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -40,13 +39,14 @@ namespace Example { public class PrivateAddToAddressBookGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new WalletApi(); + var apiInstance = new WalletApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var type = type_example; // string | Address book type var address = address_example; // string | Address in currency format, it must be in address book @@ -59,9 +59,11 @@ namespace Example Object result = apiInstance.PrivateAddToAddressBookGet(currency, type, address, name, tfa); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling WalletApi.PrivateAddToAddressBookGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -107,7 +109,6 @@ Cancel transfer ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -117,13 +118,14 @@ namespace Example { public class PrivateCancelTransferByIdGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new WalletApi(); + var apiInstance = new WalletApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var id = 12; // int? | Id of transfer var tfa = tfa_example; // string | TFA code, required when TFA is enabled for current account (optional) @@ -134,9 +136,11 @@ namespace Example Object result = apiInstance.PrivateCancelTransferByIdGet(currency, id, tfa); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling WalletApi.PrivateCancelTransferByIdGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -180,7 +184,6 @@ Cancels withdrawal request ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -190,13 +193,14 @@ namespace Example { public class PrivateCancelWithdrawalGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new WalletApi(); + var apiInstance = new WalletApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var id = 1; // decimal? | The withdrawal id @@ -206,9 +210,11 @@ namespace Example Object result = apiInstance.PrivateCancelWithdrawalGet(currency, id); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling WalletApi.PrivateCancelWithdrawalGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -251,7 +257,6 @@ Creates deposit address in currency ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -261,13 +266,14 @@ namespace Example { public class PrivateCreateDepositAddressGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new WalletApi(); + var apiInstance = new WalletApi(Configuration.Default); var currency = currency_example; // string | The currency symbol try @@ -276,9 +282,11 @@ namespace Example Object result = apiInstance.PrivateCreateDepositAddressGet(currency); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling WalletApi.PrivateCreateDepositAddressGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -320,7 +328,6 @@ Retrieves address book of given type ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -330,13 +337,14 @@ namespace Example { public class PrivateGetAddressBookGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new WalletApi(); + var apiInstance = new WalletApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var type = type_example; // string | Address book type @@ -346,9 +354,11 @@ namespace Example Object result = apiInstance.PrivateGetAddressBookGet(currency, type); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling WalletApi.PrivateGetAddressBookGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -391,7 +401,6 @@ Retrieve deposit address for currency ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -401,13 +410,14 @@ namespace Example { public class PrivateGetCurrentDepositAddressGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new WalletApi(); + var apiInstance = new WalletApi(Configuration.Default); var currency = currency_example; // string | The currency symbol try @@ -416,9 +426,11 @@ namespace Example Object result = apiInstance.PrivateGetCurrentDepositAddressGet(currency); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling WalletApi.PrivateGetCurrentDepositAddressGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -460,7 +472,6 @@ Retrieve the latest users deposits ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -470,13 +481,14 @@ namespace Example { public class PrivateGetDepositsGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new WalletApi(); + var apiInstance = new WalletApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var count = 56; // int? | Number of requested items, default - `10` (optional) var offset = 10; // int? | The offset for pagination, default - `0` (optional) @@ -487,9 +499,11 @@ namespace Example Object result = apiInstance.PrivateGetDepositsGet(currency, count, offset); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling WalletApi.PrivateGetDepositsGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -533,7 +547,6 @@ Adds new entry to address book of given type ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -543,13 +556,14 @@ namespace Example { public class PrivateGetTransfersGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new WalletApi(); + var apiInstance = new WalletApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var count = 56; // int? | Number of requested items, default - `10` (optional) var offset = 10; // int? | The offset for pagination, default - `0` (optional) @@ -560,9 +574,11 @@ namespace Example Object result = apiInstance.PrivateGetTransfersGet(currency, count, offset); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling WalletApi.PrivateGetTransfersGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -606,7 +622,6 @@ Retrieve the latest users withdrawals ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -616,13 +631,14 @@ namespace Example { public class PrivateGetWithdrawalsGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new WalletApi(); + var apiInstance = new WalletApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var count = 56; // int? | Number of requested items, default - `10` (optional) var offset = 10; // int? | The offset for pagination, default - `0` (optional) @@ -633,9 +649,11 @@ namespace Example Object result = apiInstance.PrivateGetWithdrawalsGet(currency, count, offset); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling WalletApi.PrivateGetWithdrawalsGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -679,7 +697,6 @@ Adds new entry to address book of given type ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -689,13 +706,14 @@ namespace Example { public class PrivateRemoveFromAddressBookGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new WalletApi(); + var apiInstance = new WalletApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var type = type_example; // string | Address book type var address = address_example; // string | Address in currency format, it must be in address book @@ -707,9 +725,11 @@ namespace Example Object result = apiInstance.PrivateRemoveFromAddressBookGet(currency, type, address, tfa); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling WalletApi.PrivateRemoveFromAddressBookGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -754,7 +774,6 @@ Transfer funds to a subaccount. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -764,13 +783,14 @@ namespace Example { public class PrivateSubmitTransferToSubaccountGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new WalletApi(); + var apiInstance = new WalletApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var amount = 8.14; // decimal? | Amount of funds to be transferred var destination = 1; // int? | Id of destination subaccount @@ -781,9 +801,11 @@ namespace Example Object result = apiInstance.PrivateSubmitTransferToSubaccountGet(currency, amount, destination); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling WalletApi.PrivateSubmitTransferToSubaccountGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -827,7 +849,6 @@ Transfer funds to a another user. ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -837,13 +858,14 @@ namespace Example { public class PrivateSubmitTransferToUserGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new WalletApi(); + var apiInstance = new WalletApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var amount = 8.14; // decimal? | Amount of funds to be transferred var destination = destination_example; // string | Destination address from address book @@ -855,9 +877,11 @@ namespace Example Object result = apiInstance.PrivateSubmitTransferToUserGet(currency, amount, destination, tfa); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling WalletApi.PrivateSubmitTransferToUserGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -902,7 +926,6 @@ Enable or disable deposit address creation ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -912,13 +935,14 @@ namespace Example { public class PrivateToggleDepositAddressCreationGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new WalletApi(); + var apiInstance = new WalletApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var state = true; // bool? | @@ -928,9 +952,11 @@ namespace Example Object result = apiInstance.PrivateToggleDepositAddressCreationGet(currency, state); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling WalletApi.PrivateToggleDepositAddressCreationGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } @@ -973,7 +999,6 @@ Creates a new withdrawal request ### Example ```csharp -using System; using System.Diagnostics; using Org.OpenAPITools.Api; using Org.OpenAPITools.Client; @@ -983,13 +1008,14 @@ namespace Example { public class PrivateWithdrawGetExample { - public void main() + public static void Main() { + Configuration.Default.BasePath = "https://www.deribit.com/api/v2"; // Configure HTTP basic authorization: bearerAuth Configuration.Default.Username = "YOUR_USERNAME"; Configuration.Default.Password = "YOUR_PASSWORD"; - var apiInstance = new WalletApi(); + var apiInstance = new WalletApi(Configuration.Default); var currency = currency_example; // string | The currency symbol var address = address_example; // string | Address in currency format, it must be in address book var amount = 8.14; // decimal? | Amount of funds to be withdrawn @@ -1002,9 +1028,11 @@ namespace Example Object result = apiInstance.PrivateWithdrawGet(currency, address, amount, priority, tfa); Debug.WriteLine(result); } - catch (Exception e) + catch (ApiException e) { Debug.Print("Exception when calling WalletApi.PrivateWithdrawGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); } } } diff --git a/csharp/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/csharp/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index ee7b89d..4f2b887 100644 --- a/csharp/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/csharp/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -4,7 +4,7 @@ Deribit API #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 --> @@ -81,7 +81,7 @@ OpenAPI spec version: 2.0.0 - {5F75563A-5FF8-4B20-8CE6-D15261CAA864} + {0B21CDEF-66B6-42CD-AE10-89BC72BA5CDB} Org.OpenAPITools diff --git a/csharp/src/Org.OpenAPITools/Api/AccountManagementApi.cs b/csharp/src/Org.OpenAPITools/Api/AccountManagementApi.cs index 90bf5a4..d3fc4a3 100644 --- a/csharp/src/Org.OpenAPITools/Api/AccountManagementApi.cs +++ b/csharp/src/Org.OpenAPITools/Api/AccountManagementApi.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Api/AuthenticationApi.cs b/csharp/src/Org.OpenAPITools/Api/AuthenticationApi.cs index bb4c6d1..92af4c6 100644 --- a/csharp/src/Org.OpenAPITools/Api/AuthenticationApi.cs +++ b/csharp/src/Org.OpenAPITools/Api/AuthenticationApi.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Api/InternalApi.cs b/csharp/src/Org.OpenAPITools/Api/InternalApi.cs index 049d165..f44b8cb 100644 --- a/csharp/src/Org.OpenAPITools/Api/InternalApi.cs +++ b/csharp/src/Org.OpenAPITools/Api/InternalApi.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Api/MarketDataApi.cs b/csharp/src/Org.OpenAPITools/Api/MarketDataApi.cs index 8b1eb05..2083c4b 100644 --- a/csharp/src/Org.OpenAPITools/Api/MarketDataApi.cs +++ b/csharp/src/Org.OpenAPITools/Api/MarketDataApi.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Api/PrivateApi.cs b/csharp/src/Org.OpenAPITools/Api/PrivateApi.cs index 0b8ef57..a82f7eb 100644 --- a/csharp/src/Org.OpenAPITools/Api/PrivateApi.cs +++ b/csharp/src/Org.OpenAPITools/Api/PrivateApi.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Api/PublicApi.cs b/csharp/src/Org.OpenAPITools/Api/PublicApi.cs index 348febd..033b8c0 100644 --- a/csharp/src/Org.OpenAPITools/Api/PublicApi.cs +++ b/csharp/src/Org.OpenAPITools/Api/PublicApi.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Api/SupportingApi.cs b/csharp/src/Org.OpenAPITools/Api/SupportingApi.cs index 12b2246..6a63bbc 100644 --- a/csharp/src/Org.OpenAPITools/Api/SupportingApi.cs +++ b/csharp/src/Org.OpenAPITools/Api/SupportingApi.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Api/TradingApi.cs b/csharp/src/Org.OpenAPITools/Api/TradingApi.cs index bd15bdb..c98e234 100644 --- a/csharp/src/Org.OpenAPITools/Api/TradingApi.cs +++ b/csharp/src/Org.OpenAPITools/Api/TradingApi.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Api/WalletApi.cs b/csharp/src/Org.OpenAPITools/Api/WalletApi.cs index ea7624a..33fb6b5 100644 --- a/csharp/src/Org.OpenAPITools/Api/WalletApi.cs +++ b/csharp/src/Org.OpenAPITools/Api/WalletApi.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Client/ApiClient.cs b/csharp/src/Org.OpenAPITools/Client/ApiClient.cs index 07ca06a..42d87c2 100644 --- a/csharp/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/csharp/src/Org.OpenAPITools/Client/ApiClient.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Client/ApiException.cs b/csharp/src/Org.OpenAPITools/Client/ApiException.cs index b7d68b2..823fc18 100644 --- a/csharp/src/Org.OpenAPITools/Client/ApiException.cs +++ b/csharp/src/Org.OpenAPITools/Client/ApiException.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Client/ApiResponse.cs b/csharp/src/Org.OpenAPITools/Client/ApiResponse.cs index 8777a50..37f7996 100644 --- a/csharp/src/Org.OpenAPITools/Client/ApiResponse.cs +++ b/csharp/src/Org.OpenAPITools/Client/ApiResponse.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Client/Configuration.cs b/csharp/src/Org.OpenAPITools/Client/Configuration.cs index 85393e9..219284c 100644 --- a/csharp/src/Org.OpenAPITools/Client/Configuration.cs +++ b/csharp/src/Org.OpenAPITools/Client/Configuration.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Client/ExceptionFactory.cs b/csharp/src/Org.OpenAPITools/Client/ExceptionFactory.cs index 06d49ff..df37b3d 100644 --- a/csharp/src/Org.OpenAPITools/Client/ExceptionFactory.cs +++ b/csharp/src/Org.OpenAPITools/Client/ExceptionFactory.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Client/GlobalConfiguration.cs b/csharp/src/Org.OpenAPITools/Client/GlobalConfiguration.cs index dfd7508..dc3b1dc 100644 --- a/csharp/src/Org.OpenAPITools/Client/GlobalConfiguration.cs +++ b/csharp/src/Org.OpenAPITools/Client/GlobalConfiguration.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Client/IApiAccessor.cs b/csharp/src/Org.OpenAPITools/Client/IApiAccessor.cs index b64844f..38ca428 100644 --- a/csharp/src/Org.OpenAPITools/Client/IApiAccessor.cs +++ b/csharp/src/Org.OpenAPITools/Client/IApiAccessor.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Client/IReadableConfiguration.cs b/csharp/src/Org.OpenAPITools/Client/IReadableConfiguration.cs index 56b0816..7ef84d8 100644 --- a/csharp/src/Org.OpenAPITools/Client/IReadableConfiguration.cs +++ b/csharp/src/Org.OpenAPITools/Client/IReadableConfiguration.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs b/csharp/src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs index eeae56a..fe92972 100644 --- a/csharp/src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs +++ b/csharp/src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Model/AddressBookItem.cs b/csharp/src/Org.OpenAPITools/Model/AddressBookItem.cs index 7d56d38..51648e2 100644 --- a/csharp/src/Org.OpenAPITools/Model/AddressBookItem.cs +++ b/csharp/src/Org.OpenAPITools/Model/AddressBookItem.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Model/BookSummary.cs b/csharp/src/Org.OpenAPITools/Model/BookSummary.cs index 0e670b1..5f379c6 100644 --- a/csharp/src/Org.OpenAPITools/Model/BookSummary.cs +++ b/csharp/src/Org.OpenAPITools/Model/BookSummary.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Model/Currency.cs b/csharp/src/Org.OpenAPITools/Model/Currency.cs index ad05fd9..c576172 100644 --- a/csharp/src/Org.OpenAPITools/Model/Currency.cs +++ b/csharp/src/Org.OpenAPITools/Model/Currency.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Model/CurrencyPortfolio.cs b/csharp/src/Org.OpenAPITools/Model/CurrencyPortfolio.cs index 3081cac..586f5fd 100644 --- a/csharp/src/Org.OpenAPITools/Model/CurrencyPortfolio.cs +++ b/csharp/src/Org.OpenAPITools/Model/CurrencyPortfolio.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Model/CurrencyWithdrawalPriorities.cs b/csharp/src/Org.OpenAPITools/Model/CurrencyWithdrawalPriorities.cs index 3d9b7d5..638cf6d 100644 --- a/csharp/src/Org.OpenAPITools/Model/CurrencyWithdrawalPriorities.cs +++ b/csharp/src/Org.OpenAPITools/Model/CurrencyWithdrawalPriorities.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Model/Deposit.cs b/csharp/src/Org.OpenAPITools/Model/Deposit.cs index e77a601..9f101c2 100644 --- a/csharp/src/Org.OpenAPITools/Model/Deposit.cs +++ b/csharp/src/Org.OpenAPITools/Model/Deposit.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Model/Instrument.cs b/csharp/src/Org.OpenAPITools/Model/Instrument.cs index 112deb4..7c11feb 100644 --- a/csharp/src/Org.OpenAPITools/Model/Instrument.cs +++ b/csharp/src/Org.OpenAPITools/Model/Instrument.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Model/KeyNumberPair.cs b/csharp/src/Org.OpenAPITools/Model/KeyNumberPair.cs index b304af4..381ce26 100644 --- a/csharp/src/Org.OpenAPITools/Model/KeyNumberPair.cs +++ b/csharp/src/Org.OpenAPITools/Model/KeyNumberPair.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Model/Order.cs b/csharp/src/Org.OpenAPITools/Model/Order.cs index b5f1a05..ab6a8ac 100644 --- a/csharp/src/Org.OpenAPITools/Model/Order.cs +++ b/csharp/src/Org.OpenAPITools/Model/Order.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Model/OrderIdInitialMarginPair.cs b/csharp/src/Org.OpenAPITools/Model/OrderIdInitialMarginPair.cs index 8523172..3fc7ab8 100644 --- a/csharp/src/Org.OpenAPITools/Model/OrderIdInitialMarginPair.cs +++ b/csharp/src/Org.OpenAPITools/Model/OrderIdInitialMarginPair.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Model/Portfolio.cs b/csharp/src/Org.OpenAPITools/Model/Portfolio.cs index 5cbf22c..a4182b4 100644 --- a/csharp/src/Org.OpenAPITools/Model/Portfolio.cs +++ b/csharp/src/Org.OpenAPITools/Model/Portfolio.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Model/PortfolioEth.cs b/csharp/src/Org.OpenAPITools/Model/PortfolioEth.cs index 806d8ed..c230d9a 100644 --- a/csharp/src/Org.OpenAPITools/Model/PortfolioEth.cs +++ b/csharp/src/Org.OpenAPITools/Model/PortfolioEth.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Model/Position.cs b/csharp/src/Org.OpenAPITools/Model/Position.cs index 62a6803..b65e554 100644 --- a/csharp/src/Org.OpenAPITools/Model/Position.cs +++ b/csharp/src/Org.OpenAPITools/Model/Position.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Model/PublicTrade.cs b/csharp/src/Org.OpenAPITools/Model/PublicTrade.cs index 76a4fa8..1248c2c 100644 --- a/csharp/src/Org.OpenAPITools/Model/PublicTrade.cs +++ b/csharp/src/Org.OpenAPITools/Model/PublicTrade.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Model/Settlement.cs b/csharp/src/Org.OpenAPITools/Model/Settlement.cs index 3cb9584..8c4fe9f 100644 --- a/csharp/src/Org.OpenAPITools/Model/Settlement.cs +++ b/csharp/src/Org.OpenAPITools/Model/Settlement.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Model/TradesVolumes.cs b/csharp/src/Org.OpenAPITools/Model/TradesVolumes.cs index 988634e..5811418 100644 --- a/csharp/src/Org.OpenAPITools/Model/TradesVolumes.cs +++ b/csharp/src/Org.OpenAPITools/Model/TradesVolumes.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Model/TransferItem.cs b/csharp/src/Org.OpenAPITools/Model/TransferItem.cs index fdd8d27..ea19e5e 100644 --- a/csharp/src/Org.OpenAPITools/Model/TransferItem.cs +++ b/csharp/src/Org.OpenAPITools/Model/TransferItem.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Model/Types.cs b/csharp/src/Org.OpenAPITools/Model/Types.cs index 57454ad..50b5240 100644 --- a/csharp/src/Org.OpenAPITools/Model/Types.cs +++ b/csharp/src/Org.OpenAPITools/Model/Types.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Model/UserTrade.cs b/csharp/src/Org.OpenAPITools/Model/UserTrade.cs index 0ca0c6f..fefbdd0 100644 --- a/csharp/src/Org.OpenAPITools/Model/UserTrade.cs +++ b/csharp/src/Org.OpenAPITools/Model/UserTrade.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Model/Withdrawal.cs b/csharp/src/Org.OpenAPITools/Model/Withdrawal.cs index 294ceaf..178b749 100644 --- a/csharp/src/Org.OpenAPITools/Model/Withdrawal.cs +++ b/csharp/src/Org.OpenAPITools/Model/Withdrawal.cs @@ -3,7 +3,7 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://github.com/openapitools/openapi-generator.git */ diff --git a/csharp/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/csharp/src/Org.OpenAPITools/Org.OpenAPITools.csproj index fa914d4..3a0aa9b 100644 --- a/csharp/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/csharp/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -4,7 +4,7 @@ Deribit API #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |- -- -|- -- -- -- -|- -- -- -- -|- -- -- -- -| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |- -- -|- -- -|- -- -- -- -- --| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |- -- -|- -- -|- -- -- -- -- --| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |- -- -|- -- -- -- -- --| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |- -- -|- -- -- -- -- --| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |- -- -|- -- -- -- -- --| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |- -- -|- -- -- -- -- --| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 --> @@ -12,7 +12,7 @@ OpenAPI spec version: 2.0.0 Debug AnyCPU - {5F75563A-5FF8-4B20-8CE6-D15261CAA864} + {0B21CDEF-66B6-42CD-AE10-89BC72BA5CDB} Library Properties Org.OpenAPITools @@ -28,6 +28,7 @@ OpenAPI spec version: 2.0.0 DEBUG;TRACE prompt 4 + bin\Debug\Org.OpenAPITools.xml pdbonly @@ -36,6 +37,7 @@ OpenAPI spec version: 2.0.0 TRACE prompt 4 + bin\Release\Org.OpenAPITools.xml diff --git a/erlang-client/.openapi-generator/VERSION b/erlang-client/.openapi-generator/VERSION index afa6365..d96260b 100644 --- a/erlang-client/.openapi-generator/VERSION +++ b/erlang-client/.openapi-generator/VERSION @@ -1 +1 @@ -4.0.0-SNAPSHOT \ No newline at end of file +4.0.2-SNAPSHOT \ No newline at end of file diff --git a/go/.openapi-generator/VERSION b/go/.openapi-generator/VERSION index afa6365..d96260b 100644 --- a/go/.openapi-generator/VERSION +++ b/go/.openapi-generator/VERSION @@ -1 +1 @@ -4.0.0-SNAPSHOT \ No newline at end of file +4.0.2-SNAPSHOT \ No newline at end of file diff --git a/go/api_account_management.go b/go/api_account_management.go index f9e5b94..5f3a78a 100644 --- a/go/api_account_management.go +++ b/go/api_account_management.go @@ -14,7 +14,6 @@ import ( "io/ioutil" "net/http" "net/url" - "strings" "github.com/antihax/optional" ) @@ -34,7 +33,7 @@ AccountManagementApiService Change the user name for a subaccount */ func (a *AccountManagementApiService) PrivateChangeSubaccountNameGet(ctx context.Context, sid int32, name string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -121,7 +120,7 @@ AccountManagementApiService Create a new subaccount */ func (a *AccountManagementApiService) PrivateCreateSubaccountGet(ctx context.Context) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -207,7 +206,7 @@ AccountManagementApiService Disable two factor authentication for a subaccount. */ func (a *AccountManagementApiService) PrivateDisableTfaForSubaccountGet(ctx context.Context, sid int32) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -301,7 +300,7 @@ type PrivateGetAccountSummaryGetOpts struct { func (a *AccountManagementApiService) PrivateGetAccountSummaryGet(ctx context.Context, currency string, localVarOptionals *PrivateGetAccountSummaryGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -390,7 +389,7 @@ AccountManagementApiService Retrieves the language to be used for emails. */ func (a *AccountManagementApiService) PrivateGetEmailLanguageGet(ctx context.Context) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -475,7 +474,7 @@ AccountManagementApiService Retrieves announcements that have not been marked re */ func (a *AccountManagementApiService) PrivateGetNewAnnouncementsGet(ctx context.Context) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -561,7 +560,7 @@ AccountManagementApiService Retrieve user position. */ func (a *AccountManagementApiService) PrivateGetPositionGet(ctx context.Context, instrumentName string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -665,7 +664,7 @@ type PrivateGetPositionsGetOpts struct { func (a *AccountManagementApiService) PrivateGetPositionsGet(ctx context.Context, currency string, localVarOptionals *PrivateGetPositionsGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -771,7 +770,7 @@ type PrivateGetSubaccountsGetOpts struct { func (a *AccountManagementApiService) PrivateGetSubaccountsGet(ctx context.Context, localVarOptionals *PrivateGetSubaccountsGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -870,7 +869,7 @@ AccountManagementApiService Marks an announcement as read, so it will not be sho */ func (a *AccountManagementApiService) PrivateSetAnnouncementAsReadGet(ctx context.Context, announcementId float32) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -958,7 +957,7 @@ AccountManagementApiService Assign an email address to a subaccount. User will r */ func (a *AccountManagementApiService) PrivateSetEmailForSubaccountGet(ctx context.Context, sid int32, email string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1046,7 +1045,7 @@ AccountManagementApiService Changes the language to be used for emails. */ func (a *AccountManagementApiService) PrivateSetEmailLanguageGet(ctx context.Context, language string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1134,7 +1133,7 @@ AccountManagementApiService Set the password for the subaccount */ func (a *AccountManagementApiService) PrivateSetPasswordForSubaccountGet(ctx context.Context, sid int32, password string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1223,7 +1222,7 @@ AccountManagementApiService Enable or disable sending of notifications for the s */ func (a *AccountManagementApiService) PrivateToggleNotificationsFromSubaccountGet(ctx context.Context, sid int32, state bool) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1312,7 +1311,7 @@ AccountManagementApiService Enable or disable login for a subaccount. If login i */ func (a *AccountManagementApiService) PrivateToggleSubaccountLoginGet(ctx context.Context, sid int32, state string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1399,7 +1398,7 @@ AccountManagementApiService Retrieves announcements from the last 30 days. */ func (a *AccountManagementApiService) PublicGetAnnouncementsGet(ctx context.Context) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string diff --git a/go/api_authentication.go b/go/api_authentication.go index 58f9c99..88b2fa0 100644 --- a/go/api_authentication.go +++ b/go/api_authentication.go @@ -14,7 +14,6 @@ import ( "io/ioutil" "net/http" "net/url" - "strings" "github.com/antihax/optional" ) @@ -52,7 +51,7 @@ type PublicAuthGetOpts struct { func (a *AuthenticationApiService) PublicAuthGet(ctx context.Context, grantType string, username string, password string, clientId string, clientSecret string, refreshToken string, timestamp string, signature string, localVarOptionals *PublicAuthGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string diff --git a/go/api_internal.go b/go/api_internal.go index 7059b09..793c340 100644 --- a/go/api_internal.go +++ b/go/api_internal.go @@ -14,7 +14,6 @@ import ( "io/ioutil" "net/http" "net/url" - "strings" "github.com/antihax/optional" ) @@ -43,7 +42,7 @@ type PrivateAddToAddressBookGetOpts struct { func (a *InternalApiService) PrivateAddToAddressBookGet(ctx context.Context, currency string, type_ string, address string, name string, localVarOptionals *PrivateAddToAddressBookGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -137,7 +136,7 @@ InternalApiService Disables TFA with one time recovery code */ func (a *InternalApiService) PrivateDisableTfaWithRecoveryCodeGet(ctx context.Context, password string, code string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -226,7 +225,7 @@ InternalApiService Retrieves address book of given type */ func (a *InternalApiService) PrivateGetAddressBookGet(ctx context.Context, currency string, type_ string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -323,7 +322,7 @@ type PrivateRemoveFromAddressBookGetOpts struct { func (a *InternalApiService) PrivateRemoveFromAddressBookGet(ctx context.Context, currency string, type_ string, address string, localVarOptionals *PrivateRemoveFromAddressBookGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -417,7 +416,7 @@ InternalApiService Transfer funds to a subaccount. */ func (a *InternalApiService) PrivateSubmitTransferToSubaccountGet(ctx context.Context, currency string, amount float32, destination int32) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -515,7 +514,7 @@ type PrivateSubmitTransferToUserGetOpts struct { func (a *InternalApiService) PrivateSubmitTransferToUserGet(ctx context.Context, currency string, amount float32, destination string, localVarOptionals *PrivateSubmitTransferToUserGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -608,7 +607,7 @@ InternalApiService Enable or disable deposit address creation */ func (a *InternalApiService) PrivateToggleDepositAddressCreationGet(ctx context.Context, currency string, state bool) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -695,7 +694,7 @@ InternalApiService Get information to be displayed in the footer of the website. */ func (a *InternalApiService) PublicGetFooterGet(ctx context.Context) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -781,7 +780,7 @@ InternalApiService Retrives market prices and its implied volatility of options */ func (a *InternalApiService) PublicGetOptionMarkPricesGet(ctx context.Context, currency string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -876,7 +875,7 @@ type PublicValidateFieldGetOpts struct { func (a *InternalApiService) PublicValidateFieldGet(ctx context.Context, field string, value string, localVarOptionals *PublicValidateFieldGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string diff --git a/go/api_market_data.go b/go/api_market_data.go index 58d2eb3..0642a52 100644 --- a/go/api_market_data.go +++ b/go/api_market_data.go @@ -14,7 +14,6 @@ import ( "io/ioutil" "net/http" "net/url" - "strings" "github.com/antihax/optional" ) @@ -40,7 +39,7 @@ type PublicGetBookSummaryByCurrencyGetOpts struct { func (a *MarketDataApiService) PublicGetBookSummaryByCurrencyGet(ctx context.Context, currency string, localVarOptionals *PublicGetBookSummaryByCurrencyGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -130,7 +129,7 @@ MarketDataApiService Retrieves the summary information such as open interest, 24 */ func (a *MarketDataApiService) PublicGetBookSummaryByInstrumentGet(ctx context.Context, instrumentName string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -217,7 +216,7 @@ MarketDataApiService Retrieves contract size of provided instrument. */ func (a *MarketDataApiService) PublicGetContractSizeGet(ctx context.Context, instrumentName string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -303,7 +302,7 @@ MarketDataApiService Retrieves all cryptocurrencies supported by the API. */ func (a *MarketDataApiService) PublicGetCurrenciesGet(ctx context.Context) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -396,7 +395,7 @@ type PublicGetFundingChartDataGetOpts struct { func (a *MarketDataApiService) PublicGetFundingChartDataGet(ctx context.Context, instrumentName string, localVarOptionals *PublicGetFundingChartDataGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -486,7 +485,7 @@ MarketDataApiService Provides information about historical volatility for given */ func (a *MarketDataApiService) PublicGetHistoricalVolatilityGet(ctx context.Context, currency string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -573,7 +572,7 @@ MarketDataApiService Retrieves the current index price for the instruments, for */ func (a *MarketDataApiService) PublicGetIndexGet(ctx context.Context, currency string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -669,7 +668,7 @@ type PublicGetInstrumentsGetOpts struct { func (a *MarketDataApiService) PublicGetInstrumentsGet(ctx context.Context, currency string, localVarOptionals *PublicGetInstrumentsGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -775,7 +774,7 @@ type PublicGetLastSettlementsByCurrencyGetOpts struct { func (a *MarketDataApiService) PublicGetLastSettlementsByCurrencyGet(ctx context.Context, currency string, localVarOptionals *PublicGetLastSettlementsByCurrencyGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -887,7 +886,7 @@ type PublicGetLastSettlementsByInstrumentGetOpts struct { func (a *MarketDataApiService) PublicGetLastSettlementsByInstrumentGet(ctx context.Context, instrumentName string, localVarOptionals *PublicGetLastSettlementsByInstrumentGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1001,7 +1000,7 @@ type PublicGetLastTradesByCurrencyAndTimeGetOpts struct { func (a *MarketDataApiService) PublicGetLastTradesByCurrencyAndTimeGet(ctx context.Context, currency string, startTimestamp int32, endTimestamp int32, localVarOptionals *PublicGetLastTradesByCurrencyAndTimeGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1119,7 +1118,7 @@ type PublicGetLastTradesByCurrencyGetOpts struct { func (a *MarketDataApiService) PublicGetLastTradesByCurrencyGet(ctx context.Context, currency string, localVarOptionals *PublicGetLastTradesByCurrencyGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1237,7 +1236,7 @@ type PublicGetLastTradesByInstrumentAndTimeGetOpts struct { func (a *MarketDataApiService) PublicGetLastTradesByInstrumentAndTimeGet(ctx context.Context, instrumentName string, startTimestamp int32, endTimestamp int32, localVarOptionals *PublicGetLastTradesByInstrumentAndTimeGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1350,7 +1349,7 @@ type PublicGetLastTradesByInstrumentGetOpts struct { func (a *MarketDataApiService) PublicGetLastTradesByInstrumentGet(ctx context.Context, instrumentName string, localVarOptionals *PublicGetLastTradesByInstrumentGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1459,7 +1458,7 @@ type PublicGetOrderBookGetOpts struct { func (a *MarketDataApiService) PublicGetOrderBookGet(ctx context.Context, instrumentName string, localVarOptionals *PublicGetOrderBookGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1548,7 +1547,7 @@ MarketDataApiService Retrieves aggregated 24h trade volumes for different instru */ func (a *MarketDataApiService) PublicGetTradeVolumesGet(ctx context.Context) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1636,7 +1635,7 @@ MarketDataApiService Publicly available market data used to generate a TradingVi */ func (a *MarketDataApiService) PublicGetTradingviewChartDataGet(ctx context.Context, instrumentName string, startTimestamp int32, endTimestamp int32) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1725,7 +1724,7 @@ MarketDataApiService Get ticker for an instrument. */ func (a *MarketDataApiService) PublicTickerGet(ctx context.Context, instrumentName string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string diff --git a/go/api_private.go b/go/api_private.go index adb22e7..e98d5a3 100644 --- a/go/api_private.go +++ b/go/api_private.go @@ -14,7 +14,6 @@ import ( "io/ioutil" "net/http" "net/url" - "strings" "github.com/antihax/optional" ) @@ -43,7 +42,7 @@ type PrivateAddToAddressBookGetOpts struct { func (a *PrivateApiService) PrivateAddToAddressBookGet(ctx context.Context, currency string, type_ string, address string, name string, localVarOptionals *PrivateAddToAddressBookGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -162,7 +161,7 @@ type PrivateBuyGetOpts struct { func (a *PrivateApiService) PrivateBuyGet(ctx context.Context, instrumentName string, amount float32, localVarOptionals *PrivateBuyGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -289,7 +288,7 @@ type PrivateCancelAllByCurrencyGetOpts struct { func (a *PrivateApiService) PrivateCancelAllByCurrencyGet(ctx context.Context, currency string, localVarOptionals *PrivateCancelAllByCurrencyGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -389,7 +388,7 @@ type PrivateCancelAllByInstrumentGetOpts struct { func (a *PrivateApiService) PrivateCancelAllByInstrumentGet(ctx context.Context, instrumentName string, localVarOptionals *PrivateCancelAllByInstrumentGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -478,7 +477,7 @@ PrivateApiService This method cancels all users orders and stop orders within al */ func (a *PrivateApiService) PrivateCancelAllGet(ctx context.Context) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -564,7 +563,7 @@ PrivateApiService Cancel an order, specified by order id */ func (a *PrivateApiService) PrivateCancelGet(ctx context.Context, orderId string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -659,7 +658,7 @@ type PrivateCancelTransferByIdGetOpts struct { func (a *PrivateApiService) PrivateCancelTransferByIdGet(ctx context.Context, currency string, id int32, localVarOptionals *PrivateCancelTransferByIdGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -751,7 +750,7 @@ PrivateApiService Cancels withdrawal request */ func (a *PrivateApiService) PrivateCancelWithdrawalGet(ctx context.Context, currency string, id float32) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -840,7 +839,7 @@ PrivateApiService Change the user name for a subaccount */ func (a *PrivateApiService) PrivateChangeSubaccountNameGet(ctx context.Context, sid int32, name string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -936,7 +935,7 @@ type PrivateClosePositionGetOpts struct { func (a *PrivateApiService) PrivateClosePositionGet(ctx context.Context, instrumentName string, type_ string, localVarOptionals *PrivateClosePositionGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1027,7 +1026,7 @@ PrivateApiService Creates deposit address in currency */ func (a *PrivateApiService) PrivateCreateDepositAddressGet(ctx context.Context, currency string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1113,7 +1112,7 @@ PrivateApiService Create a new subaccount */ func (a *PrivateApiService) PrivateCreateSubaccountGet(ctx context.Context) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1199,7 +1198,7 @@ PrivateApiService Disable two factor authentication for a subaccount. */ func (a *PrivateApiService) PrivateDisableTfaForSubaccountGet(ctx context.Context, sid int32) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1287,7 +1286,7 @@ PrivateApiService Disables TFA with one time recovery code */ func (a *PrivateApiService) PrivateDisableTfaWithRecoveryCodeGet(ctx context.Context, password string, code string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1388,7 +1387,7 @@ type PrivateEditGetOpts struct { func (a *PrivateApiService) PrivateEditGet(ctx context.Context, orderId string, amount float32, price float32, localVarOptionals *PrivateEditGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1493,7 +1492,7 @@ type PrivateGetAccountSummaryGetOpts struct { func (a *PrivateApiService) PrivateGetAccountSummaryGet(ctx context.Context, currency string, localVarOptionals *PrivateGetAccountSummaryGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1584,7 +1583,7 @@ PrivateApiService Retrieves address book of given type */ func (a *PrivateApiService) PrivateGetAddressBookGet(ctx context.Context, currency string, type_ string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1672,7 +1671,7 @@ PrivateApiService Retrieve deposit address for currency */ func (a *PrivateApiService) PrivateGetCurrentDepositAddressGet(ctx context.Context, currency string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1768,7 +1767,7 @@ type PrivateGetDepositsGetOpts struct { func (a *PrivateApiService) PrivateGetDepositsGet(ctx context.Context, currency string, localVarOptionals *PrivateGetDepositsGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1860,7 +1859,7 @@ PrivateApiService Retrieves the language to be used for emails. */ func (a *PrivateApiService) PrivateGetEmailLanguageGet(ctx context.Context) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1948,7 +1947,7 @@ PrivateApiService Get margins for given instrument, amount and price. */ func (a *PrivateApiService) PrivateGetMarginsGet(ctx context.Context, instrumentName string, amount float32, price float32) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -2036,7 +2035,7 @@ PrivateApiService Retrieves announcements that have not been marked read by the */ func (a *PrivateApiService) PrivateGetNewAnnouncementsGet(ctx context.Context) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -2131,7 +2130,7 @@ type PrivateGetOpenOrdersByCurrencyGetOpts struct { func (a *PrivateApiService) PrivateGetOpenOrdersByCurrencyGet(ctx context.Context, currency string, localVarOptionals *PrivateGetOpenOrdersByCurrencyGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -2231,7 +2230,7 @@ type PrivateGetOpenOrdersByInstrumentGetOpts struct { func (a *PrivateApiService) PrivateGetOpenOrdersByInstrumentGet(ctx context.Context, instrumentName string, localVarOptionals *PrivateGetOpenOrdersByInstrumentGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -2336,7 +2335,7 @@ type PrivateGetOrderHistoryByCurrencyGetOpts struct { func (a *PrivateApiService) PrivateGetOrderHistoryByCurrencyGet(ctx context.Context, currency string, localVarOptionals *PrivateGetOrderHistoryByCurrencyGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -2451,7 +2450,7 @@ type PrivateGetOrderHistoryByInstrumentGetOpts struct { func (a *PrivateApiService) PrivateGetOrderHistoryByInstrumentGet(ctx context.Context, instrumentName string, localVarOptionals *PrivateGetOrderHistoryByInstrumentGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -2550,7 +2549,7 @@ PrivateApiService Retrieves initial margins of given orders */ func (a *PrivateApiService) PrivateGetOrderMarginByIdsGet(ctx context.Context, ids []string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -2637,7 +2636,7 @@ PrivateApiService Retrieve the current state of an order. */ func (a *PrivateApiService) PrivateGetOrderStateGet(ctx context.Context, orderId string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -2734,7 +2733,7 @@ PrivateApiService Retrieve user position. */ func (a *PrivateApiService) PrivateGetPositionGet(ctx context.Context, instrumentName string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -2838,7 +2837,7 @@ type PrivateGetPositionsGetOpts struct { func (a *PrivateApiService) PrivateGetPositionsGet(ctx context.Context, currency string, localVarOptionals *PrivateGetPositionsGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -2947,7 +2946,7 @@ type PrivateGetSettlementHistoryByCurrencyGetOpts struct { func (a *PrivateApiService) PrivateGetSettlementHistoryByCurrencyGet(ctx context.Context, currency string, localVarOptionals *PrivateGetSettlementHistoryByCurrencyGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -3049,7 +3048,7 @@ type PrivateGetSettlementHistoryByInstrumentGetOpts struct { func (a *PrivateApiService) PrivateGetSettlementHistoryByInstrumentGet(ctx context.Context, instrumentName string, localVarOptionals *PrivateGetSettlementHistoryByInstrumentGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -3148,7 +3147,7 @@ type PrivateGetSubaccountsGetOpts struct { func (a *PrivateApiService) PrivateGetSubaccountsGet(ctx context.Context, localVarOptionals *PrivateGetSubaccountsGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -3256,7 +3255,7 @@ type PrivateGetTransfersGetOpts struct { func (a *PrivateApiService) PrivateGetTransfersGet(ctx context.Context, currency string, localVarOptionals *PrivateGetTransfersGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -3364,7 +3363,7 @@ type PrivateGetUserTradesByCurrencyAndTimeGetOpts struct { func (a *PrivateApiService) PrivateGetUserTradesByCurrencyAndTimeGet(ctx context.Context, currency string, startTimestamp int32, endTimestamp int32, localVarOptionals *PrivateGetUserTradesByCurrencyAndTimeGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -3482,7 +3481,7 @@ type PrivateGetUserTradesByCurrencyGetOpts struct { func (a *PrivateApiService) PrivateGetUserTradesByCurrencyGet(ctx context.Context, currency string, localVarOptionals *PrivateGetUserTradesByCurrencyGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -3600,7 +3599,7 @@ type PrivateGetUserTradesByInstrumentAndTimeGetOpts struct { func (a *PrivateApiService) PrivateGetUserTradesByInstrumentAndTimeGet(ctx context.Context, instrumentName string, startTimestamp int32, endTimestamp int32, localVarOptionals *PrivateGetUserTradesByInstrumentAndTimeGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -3713,7 +3712,7 @@ type PrivateGetUserTradesByInstrumentGetOpts struct { func (a *PrivateApiService) PrivateGetUserTradesByInstrumentGet(ctx context.Context, instrumentName string, localVarOptionals *PrivateGetUserTradesByInstrumentGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -3822,7 +3821,7 @@ type PrivateGetUserTradesByOrderGetOpts struct { func (a *PrivateApiService) PrivateGetUserTradesByOrderGet(ctx context.Context, orderId string, localVarOptionals *PrivateGetUserTradesByOrderGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -3921,7 +3920,7 @@ type PrivateGetWithdrawalsGetOpts struct { func (a *PrivateApiService) PrivateGetWithdrawalsGet(ctx context.Context, currency string, localVarOptionals *PrivateGetWithdrawalsGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -4023,7 +4022,7 @@ type PrivateRemoveFromAddressBookGetOpts struct { func (a *PrivateApiService) PrivateRemoveFromAddressBookGet(ctx context.Context, currency string, type_ string, address string, localVarOptionals *PrivateRemoveFromAddressBookGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -4141,7 +4140,7 @@ type PrivateSellGetOpts struct { func (a *PrivateApiService) PrivateSellGet(ctx context.Context, instrumentName string, amount float32, localVarOptionals *PrivateSellGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -4259,7 +4258,7 @@ PrivateApiService Marks an announcement as read, so it will not be shown in `get */ func (a *PrivateApiService) PrivateSetAnnouncementAsReadGet(ctx context.Context, announcementId float32) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -4347,7 +4346,7 @@ PrivateApiService Assign an email address to a subaccount. User will receive an */ func (a *PrivateApiService) PrivateSetEmailForSubaccountGet(ctx context.Context, sid int32, email string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -4435,7 +4434,7 @@ PrivateApiService Changes the language to be used for emails. */ func (a *PrivateApiService) PrivateSetEmailLanguageGet(ctx context.Context, language string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -4523,7 +4522,7 @@ PrivateApiService Set the password for the subaccount */ func (a *PrivateApiService) PrivateSetPasswordForSubaccountGet(ctx context.Context, sid int32, password string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -4613,7 +4612,7 @@ PrivateApiService Transfer funds to a subaccount. */ func (a *PrivateApiService) PrivateSubmitTransferToSubaccountGet(ctx context.Context, currency string, amount float32, destination int32) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -4711,7 +4710,7 @@ type PrivateSubmitTransferToUserGetOpts struct { func (a *PrivateApiService) PrivateSubmitTransferToUserGet(ctx context.Context, currency string, amount float32, destination string, localVarOptionals *PrivateSubmitTransferToUserGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -4804,7 +4803,7 @@ PrivateApiService Enable or disable deposit address creation */ func (a *PrivateApiService) PrivateToggleDepositAddressCreationGet(ctx context.Context, currency string, state bool) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -4893,7 +4892,7 @@ PrivateApiService Enable or disable sending of notifications for the subaccount. */ func (a *PrivateApiService) PrivateToggleNotificationsFromSubaccountGet(ctx context.Context, sid int32, state bool) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -4982,7 +4981,7 @@ PrivateApiService Enable or disable login for a subaccount. If login is disabled */ func (a *PrivateApiService) PrivateToggleSubaccountLoginGet(ctx context.Context, sid int32, state string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -5081,7 +5080,7 @@ type PrivateWithdrawGetOpts struct { func (a *PrivateApiService) PrivateWithdrawGet(ctx context.Context, currency string, address string, amount float32, localVarOptionals *PrivateWithdrawGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string diff --git a/go/api_public.go b/go/api_public.go index 72b59b7..fa33658 100644 --- a/go/api_public.go +++ b/go/api_public.go @@ -14,7 +14,6 @@ import ( "io/ioutil" "net/http" "net/url" - "strings" "github.com/antihax/optional" ) @@ -52,7 +51,7 @@ type PublicAuthGetOpts struct { func (a *PublicApiService) PublicAuthGet(ctx context.Context, grantType string, username string, password string, clientId string, clientSecret string, refreshToken string, timestamp string, signature string, localVarOptionals *PublicAuthGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -164,7 +163,7 @@ PublicApiService Retrieves announcements from the last 30 days. */ func (a *PublicApiService) PublicGetAnnouncementsGet(ctx context.Context) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -257,7 +256,7 @@ type PublicGetBookSummaryByCurrencyGetOpts struct { func (a *PublicApiService) PublicGetBookSummaryByCurrencyGet(ctx context.Context, currency string, localVarOptionals *PublicGetBookSummaryByCurrencyGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -347,7 +346,7 @@ PublicApiService Retrieves the summary information such as open interest, 24h vo */ func (a *PublicApiService) PublicGetBookSummaryByInstrumentGet(ctx context.Context, instrumentName string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -434,7 +433,7 @@ PublicApiService Retrieves contract size of provided instrument. */ func (a *PublicApiService) PublicGetContractSizeGet(ctx context.Context, instrumentName string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -520,7 +519,7 @@ PublicApiService Retrieves all cryptocurrencies supported by the API. */ func (a *PublicApiService) PublicGetCurrenciesGet(ctx context.Context) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -613,7 +612,7 @@ type PublicGetFundingChartDataGetOpts struct { func (a *PublicApiService) PublicGetFundingChartDataGet(ctx context.Context, instrumentName string, localVarOptionals *PublicGetFundingChartDataGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -703,7 +702,7 @@ PublicApiService Provides information about historical volatility for given cryp */ func (a *PublicApiService) PublicGetHistoricalVolatilityGet(ctx context.Context, currency string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -790,7 +789,7 @@ PublicApiService Retrieves the current index price for the instruments, for the */ func (a *PublicApiService) PublicGetIndexGet(ctx context.Context, currency string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -886,7 +885,7 @@ type PublicGetInstrumentsGetOpts struct { func (a *PublicApiService) PublicGetInstrumentsGet(ctx context.Context, currency string, localVarOptionals *PublicGetInstrumentsGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -992,7 +991,7 @@ type PublicGetLastSettlementsByCurrencyGetOpts struct { func (a *PublicApiService) PublicGetLastSettlementsByCurrencyGet(ctx context.Context, currency string, localVarOptionals *PublicGetLastSettlementsByCurrencyGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1104,7 +1103,7 @@ type PublicGetLastSettlementsByInstrumentGetOpts struct { func (a *PublicApiService) PublicGetLastSettlementsByInstrumentGet(ctx context.Context, instrumentName string, localVarOptionals *PublicGetLastSettlementsByInstrumentGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1218,7 +1217,7 @@ type PublicGetLastTradesByCurrencyAndTimeGetOpts struct { func (a *PublicApiService) PublicGetLastTradesByCurrencyAndTimeGet(ctx context.Context, currency string, startTimestamp int32, endTimestamp int32, localVarOptionals *PublicGetLastTradesByCurrencyAndTimeGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1336,7 +1335,7 @@ type PublicGetLastTradesByCurrencyGetOpts struct { func (a *PublicApiService) PublicGetLastTradesByCurrencyGet(ctx context.Context, currency string, localVarOptionals *PublicGetLastTradesByCurrencyGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1454,7 +1453,7 @@ type PublicGetLastTradesByInstrumentAndTimeGetOpts struct { func (a *PublicApiService) PublicGetLastTradesByInstrumentAndTimeGet(ctx context.Context, instrumentName string, startTimestamp int32, endTimestamp int32, localVarOptionals *PublicGetLastTradesByInstrumentAndTimeGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1567,7 +1566,7 @@ type PublicGetLastTradesByInstrumentGetOpts struct { func (a *PublicApiService) PublicGetLastTradesByInstrumentGet(ctx context.Context, instrumentName string, localVarOptionals *PublicGetLastTradesByInstrumentGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1676,7 +1675,7 @@ type PublicGetOrderBookGetOpts struct { func (a *PublicApiService) PublicGetOrderBookGet(ctx context.Context, instrumentName string, localVarOptionals *PublicGetOrderBookGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1765,7 +1764,7 @@ PublicApiService Retrieves the current time (in milliseconds). This API endpoint */ func (a *PublicApiService) PublicGetTimeGet(ctx context.Context) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1850,7 +1849,7 @@ PublicApiService Retrieves aggregated 24h trade volumes for different instrument */ func (a *PublicApiService) PublicGetTradeVolumesGet(ctx context.Context) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1938,7 +1937,7 @@ PublicApiService Publicly available market data used to generate a TradingView c */ func (a *PublicApiService) PublicGetTradingviewChartDataGet(ctx context.Context, instrumentName string, startTimestamp int32, endTimestamp int32) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -2033,7 +2032,7 @@ type PublicTestGetOpts struct { func (a *PublicApiService) PublicTestGet(ctx context.Context, localVarOptionals *PublicTestGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -2122,7 +2121,7 @@ PublicApiService Get ticker for an instrument. */ func (a *PublicApiService) PublicTickerGet(ctx context.Context, instrumentName string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -2217,7 +2216,7 @@ type PublicValidateFieldGetOpts struct { func (a *PublicApiService) PublicValidateFieldGet(ctx context.Context, field string, value string, localVarOptionals *PublicValidateFieldGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string diff --git a/go/api_supporting.go b/go/api_supporting.go index ae02faf..4cbc324 100644 --- a/go/api_supporting.go +++ b/go/api_supporting.go @@ -14,7 +14,6 @@ import ( "io/ioutil" "net/http" "net/url" - "strings" "github.com/antihax/optional" ) @@ -32,7 +31,7 @@ SupportingApiService Retrieves the current time (in milliseconds). This API endp */ func (a *SupportingApiService) PublicGetTimeGet(ctx context.Context) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -124,7 +123,7 @@ type PublicTestGetOpts struct { func (a *SupportingApiService) PublicTestGet(ctx context.Context, localVarOptionals *PublicTestGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string diff --git a/go/api_trading.go b/go/api_trading.go index 68158b1..5d59984 100644 --- a/go/api_trading.go +++ b/go/api_trading.go @@ -14,7 +14,6 @@ import ( "io/ioutil" "net/http" "net/url" - "strings" "github.com/antihax/optional" ) @@ -59,7 +58,7 @@ type PrivateBuyGetOpts struct { func (a *TradingApiService) PrivateBuyGet(ctx context.Context, instrumentName string, amount float32, localVarOptionals *PrivateBuyGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -186,7 +185,7 @@ type PrivateCancelAllByCurrencyGetOpts struct { func (a *TradingApiService) PrivateCancelAllByCurrencyGet(ctx context.Context, currency string, localVarOptionals *PrivateCancelAllByCurrencyGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -286,7 +285,7 @@ type PrivateCancelAllByInstrumentGetOpts struct { func (a *TradingApiService) PrivateCancelAllByInstrumentGet(ctx context.Context, instrumentName string, localVarOptionals *PrivateCancelAllByInstrumentGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -375,7 +374,7 @@ TradingApiService This method cancels all users orders and stop orders within al */ func (a *TradingApiService) PrivateCancelAllGet(ctx context.Context) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -461,7 +460,7 @@ TradingApiService Cancel an order, specified by order id */ func (a *TradingApiService) PrivateCancelGet(ctx context.Context, orderId string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -556,7 +555,7 @@ type PrivateClosePositionGetOpts struct { func (a *TradingApiService) PrivateClosePositionGet(ctx context.Context, instrumentName string, type_ string, localVarOptionals *PrivateClosePositionGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -660,7 +659,7 @@ type PrivateEditGetOpts struct { func (a *TradingApiService) PrivateEditGet(ctx context.Context, orderId string, amount float32, price float32, localVarOptionals *PrivateEditGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -760,7 +759,7 @@ TradingApiService Get margins for given instrument, amount and price. */ func (a *TradingApiService) PrivateGetMarginsGet(ctx context.Context, instrumentName string, amount float32, price float32) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -858,7 +857,7 @@ type PrivateGetOpenOrdersByCurrencyGetOpts struct { func (a *TradingApiService) PrivateGetOpenOrdersByCurrencyGet(ctx context.Context, currency string, localVarOptionals *PrivateGetOpenOrdersByCurrencyGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -958,7 +957,7 @@ type PrivateGetOpenOrdersByInstrumentGetOpts struct { func (a *TradingApiService) PrivateGetOpenOrdersByInstrumentGet(ctx context.Context, instrumentName string, localVarOptionals *PrivateGetOpenOrdersByInstrumentGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1063,7 +1062,7 @@ type PrivateGetOrderHistoryByCurrencyGetOpts struct { func (a *TradingApiService) PrivateGetOrderHistoryByCurrencyGet(ctx context.Context, currency string, localVarOptionals *PrivateGetOrderHistoryByCurrencyGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1178,7 +1177,7 @@ type PrivateGetOrderHistoryByInstrumentGetOpts struct { func (a *TradingApiService) PrivateGetOrderHistoryByInstrumentGet(ctx context.Context, instrumentName string, localVarOptionals *PrivateGetOrderHistoryByInstrumentGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1277,7 +1276,7 @@ TradingApiService Retrieves initial margins of given orders */ func (a *TradingApiService) PrivateGetOrderMarginByIdsGet(ctx context.Context, ids []string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1364,7 +1363,7 @@ TradingApiService Retrieve the current state of an order. */ func (a *TradingApiService) PrivateGetOrderStateGet(ctx context.Context, orderId string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1470,7 +1469,7 @@ type PrivateGetSettlementHistoryByCurrencyGetOpts struct { func (a *TradingApiService) PrivateGetSettlementHistoryByCurrencyGet(ctx context.Context, currency string, localVarOptionals *PrivateGetSettlementHistoryByCurrencyGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1572,7 +1571,7 @@ type PrivateGetSettlementHistoryByInstrumentGetOpts struct { func (a *TradingApiService) PrivateGetSettlementHistoryByInstrumentGet(ctx context.Context, instrumentName string, localVarOptionals *PrivateGetSettlementHistoryByInstrumentGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1680,7 +1679,7 @@ type PrivateGetUserTradesByCurrencyAndTimeGetOpts struct { func (a *TradingApiService) PrivateGetUserTradesByCurrencyAndTimeGet(ctx context.Context, currency string, startTimestamp int32, endTimestamp int32, localVarOptionals *PrivateGetUserTradesByCurrencyAndTimeGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1798,7 +1797,7 @@ type PrivateGetUserTradesByCurrencyGetOpts struct { func (a *TradingApiService) PrivateGetUserTradesByCurrencyGet(ctx context.Context, currency string, localVarOptionals *PrivateGetUserTradesByCurrencyGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1916,7 +1915,7 @@ type PrivateGetUserTradesByInstrumentAndTimeGetOpts struct { func (a *TradingApiService) PrivateGetUserTradesByInstrumentAndTimeGet(ctx context.Context, instrumentName string, startTimestamp int32, endTimestamp int32, localVarOptionals *PrivateGetUserTradesByInstrumentAndTimeGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -2029,7 +2028,7 @@ type PrivateGetUserTradesByInstrumentGetOpts struct { func (a *TradingApiService) PrivateGetUserTradesByInstrumentGet(ctx context.Context, instrumentName string, localVarOptionals *PrivateGetUserTradesByInstrumentGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -2138,7 +2137,7 @@ type PrivateGetUserTradesByOrderGetOpts struct { func (a *TradingApiService) PrivateGetUserTradesByOrderGet(ctx context.Context, orderId string, localVarOptionals *PrivateGetUserTradesByOrderGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -2254,7 +2253,7 @@ type PrivateSellGetOpts struct { func (a *TradingApiService) PrivateSellGet(ctx context.Context, instrumentName string, amount float32, localVarOptionals *PrivateSellGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string diff --git a/go/api_wallet.go b/go/api_wallet.go index d27e0d5..9627af1 100644 --- a/go/api_wallet.go +++ b/go/api_wallet.go @@ -14,7 +14,6 @@ import ( "io/ioutil" "net/http" "net/url" - "strings" "github.com/antihax/optional" ) @@ -43,7 +42,7 @@ type PrivateAddToAddressBookGetOpts struct { func (a *WalletApiService) PrivateAddToAddressBookGet(ctx context.Context, currency string, type_ string, address string, name string, localVarOptionals *PrivateAddToAddressBookGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -144,7 +143,7 @@ type PrivateCancelTransferByIdGetOpts struct { func (a *WalletApiService) PrivateCancelTransferByIdGet(ctx context.Context, currency string, id int32, localVarOptionals *PrivateCancelTransferByIdGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -236,7 +235,7 @@ WalletApiService Cancels withdrawal request */ func (a *WalletApiService) PrivateCancelWithdrawalGet(ctx context.Context, currency string, id float32) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -324,7 +323,7 @@ WalletApiService Creates deposit address in currency */ func (a *WalletApiService) PrivateCreateDepositAddressGet(ctx context.Context, currency string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -412,7 +411,7 @@ WalletApiService Retrieves address book of given type */ func (a *WalletApiService) PrivateGetAddressBookGet(ctx context.Context, currency string, type_ string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -500,7 +499,7 @@ WalletApiService Retrieve deposit address for currency */ func (a *WalletApiService) PrivateGetCurrentDepositAddressGet(ctx context.Context, currency string) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -596,7 +595,7 @@ type PrivateGetDepositsGetOpts struct { func (a *WalletApiService) PrivateGetDepositsGet(ctx context.Context, currency string, localVarOptionals *PrivateGetDepositsGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -698,7 +697,7 @@ type PrivateGetTransfersGetOpts struct { func (a *WalletApiService) PrivateGetTransfersGet(ctx context.Context, currency string, localVarOptionals *PrivateGetTransfersGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -800,7 +799,7 @@ type PrivateGetWithdrawalsGetOpts struct { func (a *WalletApiService) PrivateGetWithdrawalsGet(ctx context.Context, currency string, localVarOptionals *PrivateGetWithdrawalsGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -902,7 +901,7 @@ type PrivateRemoveFromAddressBookGetOpts struct { func (a *WalletApiService) PrivateRemoveFromAddressBookGet(ctx context.Context, currency string, type_ string, address string, localVarOptionals *PrivateRemoveFromAddressBookGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -996,7 +995,7 @@ WalletApiService Transfer funds to a subaccount. */ func (a *WalletApiService) PrivateSubmitTransferToSubaccountGet(ctx context.Context, currency string, amount float32, destination int32) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1094,7 +1093,7 @@ type PrivateSubmitTransferToUserGetOpts struct { func (a *WalletApiService) PrivateSubmitTransferToUserGet(ctx context.Context, currency string, amount float32, destination string, localVarOptionals *PrivateSubmitTransferToUserGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1187,7 +1186,7 @@ WalletApiService Enable or disable deposit address creation */ func (a *WalletApiService) PrivateToggleDepositAddressCreationGet(ctx context.Context, currency string, state bool) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string @@ -1286,7 +1285,7 @@ type PrivateWithdrawGetOpts struct { func (a *WalletApiService) PrivateWithdrawGet(ctx context.Context, currency string, address string, amount float32, localVarOptionals *PrivateWithdrawGetOpts) (map[string]interface{}, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHttpMethod = http.MethodGet localVarPostBody interface{} localVarFormFileName string localVarFileName string diff --git a/go/client.go b/go/client.go index 2c4543f..1561b0d 100644 --- a/go/client.go +++ b/go/client.go @@ -396,7 +396,7 @@ func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err e } else if jsonCheck.MatchString(contentType) { err = json.NewEncoder(bodyBuf).Encode(body) } else if xmlCheck.MatchString(contentType) { - xml.NewEncoder(bodyBuf).Encode(body) + err = xml.NewEncoder(bodyBuf).Encode(body) } if err != nil { diff --git a/java/.openapi-generator/VERSION b/java/.openapi-generator/VERSION index afa6365..d96260b 100644 --- a/java/.openapi-generator/VERSION +++ b/java/.openapi-generator/VERSION @@ -1 +1 @@ -4.0.0-SNAPSHOT \ No newline at end of file +4.0.2-SNAPSHOT \ No newline at end of file diff --git a/java/README.md b/java/README.md index 809ff17..edb2fab 100644 --- a/java/README.md +++ b/java/README.md @@ -2,7 +2,7 @@ Deribit API - API version: 2.0.0 - - Build date: 2019-05-31T10:31:59.717+02:00[Europe/Paris] + - Build date: 2019-06-03T12:11:21.378+02:00[Europe/Paris] #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods diff --git a/java/docs/AccountManagementApi.md b/java/docs/AccountManagementApi.md index db757a0..9e3f2c3 100644 --- a/java/docs/AccountManagementApi.md +++ b/java/docs/AccountManagementApi.md @@ -31,28 +31,37 @@ Change the user name for a subaccount ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.AccountManagementApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -AccountManagementApi apiInstance = new AccountManagementApi(); -Integer sid = 56; // Integer | The user id for the subaccount -String name = newUserName; // String | The new user name -try { - Object result = apiInstance.privateChangeSubaccountNameGet(sid, name); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling AccountManagementApi#privateChangeSubaccountNameGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AccountManagementApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + AccountManagementApi apiInstance = new AccountManagementApi(defaultClient); + Integer sid = 56; // Integer | The user id for the subaccount + String name = newUserName; // String | The new user name + try { + Object result = apiInstance.privateChangeSubaccountNameGet(sid, name); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AccountManagementApi#privateChangeSubaccountNameGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -76,6 +85,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateCreateSubaccountGet** > Object privateCreateSubaccountGet() @@ -85,26 +99,35 @@ Create a new subaccount ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.AccountManagementApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -AccountManagementApi apiInstance = new AccountManagementApi(); -try { - Object result = apiInstance.privateCreateSubaccountGet(); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling AccountManagementApi#privateCreateSubaccountGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AccountManagementApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + AccountManagementApi apiInstance = new AccountManagementApi(defaultClient); + try { + Object result = apiInstance.privateCreateSubaccountGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AccountManagementApi#privateCreateSubaccountGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -124,6 +147,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateDisableTfaForSubaccountGet** > Object privateDisableTfaForSubaccountGet(sid) @@ -133,27 +161,36 @@ Disable two factor authentication for a subaccount. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.AccountManagementApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -AccountManagementApi apiInstance = new AccountManagementApi(); -Integer sid = 56; // Integer | The user id for the subaccount -try { - Object result = apiInstance.privateDisableTfaForSubaccountGet(sid); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling AccountManagementApi#privateDisableTfaForSubaccountGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AccountManagementApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + AccountManagementApi apiInstance = new AccountManagementApi(defaultClient); + Integer sid = 56; // Integer | The user id for the subaccount + try { + Object result = apiInstance.privateDisableTfaForSubaccountGet(sid); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AccountManagementApi#privateDisableTfaForSubaccountGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -176,6 +213,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateGetAccountSummaryGet** > Object privateGetAccountSummaryGet(currency, extended) @@ -185,28 +227,37 @@ Retrieves user account summary. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.AccountManagementApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -AccountManagementApi apiInstance = new AccountManagementApi(); -String currency = "currency_example"; // String | The currency symbol -Boolean extended = false; // Boolean | Include additional fields -try { - Object result = apiInstance.privateGetAccountSummaryGet(currency, extended); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling AccountManagementApi#privateGetAccountSummaryGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AccountManagementApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + AccountManagementApi apiInstance = new AccountManagementApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + Boolean extended = false; // Boolean | Include additional fields + try { + Object result = apiInstance.privateGetAccountSummaryGet(currency, extended); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AccountManagementApi#privateGetAccountSummaryGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -230,6 +281,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetEmailLanguageGet** > Object privateGetEmailLanguageGet() @@ -239,26 +295,35 @@ Retrieves the language to be used for emails. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.AccountManagementApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -AccountManagementApi apiInstance = new AccountManagementApi(); -try { - Object result = apiInstance.privateGetEmailLanguageGet(); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling AccountManagementApi#privateGetEmailLanguageGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AccountManagementApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + AccountManagementApi apiInstance = new AccountManagementApi(defaultClient); + try { + Object result = apiInstance.privateGetEmailLanguageGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AccountManagementApi#privateGetEmailLanguageGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -278,6 +343,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetNewAnnouncementsGet** > Object privateGetNewAnnouncementsGet() @@ -287,26 +357,35 @@ Retrieves announcements that have not been marked read by the user. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.AccountManagementApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -AccountManagementApi apiInstance = new AccountManagementApi(); -try { - Object result = apiInstance.privateGetNewAnnouncementsGet(); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling AccountManagementApi#privateGetNewAnnouncementsGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AccountManagementApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + AccountManagementApi apiInstance = new AccountManagementApi(defaultClient); + try { + Object result = apiInstance.privateGetNewAnnouncementsGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AccountManagementApi#privateGetNewAnnouncementsGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -326,6 +405,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetPositionGet** > Object privateGetPositionGet(instrumentName) @@ -335,27 +419,36 @@ Retrieve user position. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.AccountManagementApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -AccountManagementApi apiInstance = new AccountManagementApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -try { - Object result = apiInstance.privateGetPositionGet(instrumentName); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling AccountManagementApi#privateGetPositionGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AccountManagementApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + AccountManagementApi apiInstance = new AccountManagementApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + try { + Object result = apiInstance.privateGetPositionGet(instrumentName); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AccountManagementApi#privateGetPositionGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -378,6 +471,12 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | When successful returns position | - | +**400** | When some error occurs | - | + # **privateGetPositionsGet** > Object privateGetPositionsGet(currency, kind) @@ -387,28 +486,37 @@ Retrieve user positions. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.AccountManagementApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -AccountManagementApi apiInstance = new AccountManagementApi(); -String currency = "currency_example"; // String | -String kind = "kind_example"; // String | Kind filter on positions -try { - Object result = apiInstance.privateGetPositionsGet(currency, kind); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling AccountManagementApi#privateGetPositionsGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AccountManagementApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + AccountManagementApi apiInstance = new AccountManagementApi(defaultClient); + String currency = "currency_example"; // String | + String kind = "kind_example"; // String | Kind filter on positions + try { + Object result = apiInstance.privateGetPositionsGet(currency, kind); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AccountManagementApi#privateGetPositionsGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -432,6 +540,12 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | When successful returns array of positions | - | +**400** | When some error occurs | - | + # **privateGetSubaccountsGet** > Object privateGetSubaccountsGet(withPortfolio) @@ -441,27 +555,36 @@ Get information about subaccounts ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.AccountManagementApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -AccountManagementApi apiInstance = new AccountManagementApi(); -Boolean withPortfolio = true; // Boolean | -try { - Object result = apiInstance.privateGetSubaccountsGet(withPortfolio); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling AccountManagementApi#privateGetSubaccountsGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AccountManagementApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + AccountManagementApi apiInstance = new AccountManagementApi(defaultClient); + Boolean withPortfolio = true; // Boolean | + try { + Object result = apiInstance.privateGetSubaccountsGet(withPortfolio); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AccountManagementApi#privateGetSubaccountsGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -484,6 +607,12 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | +**401** | not authorised | - | + # **privateSetAnnouncementAsReadGet** > Object privateSetAnnouncementAsReadGet(announcementId) @@ -493,27 +622,36 @@ Marks an announcement as read, so it will not be shown in `get_new_announce ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.AccountManagementApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -AccountManagementApi apiInstance = new AccountManagementApi(); -BigDecimal announcementId = new BigDecimal(); // BigDecimal | the ID of the announcement -try { - Object result = apiInstance.privateSetAnnouncementAsReadGet(announcementId); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling AccountManagementApi#privateSetAnnouncementAsReadGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AccountManagementApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + AccountManagementApi apiInstance = new AccountManagementApi(defaultClient); + BigDecimal announcementId = new BigDecimal(); // BigDecimal | the ID of the announcement + try { + Object result = apiInstance.privateSetAnnouncementAsReadGet(announcementId); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AccountManagementApi#privateSetAnnouncementAsReadGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -536,6 +674,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateSetEmailForSubaccountGet** > Object privateSetEmailForSubaccountGet(sid, email) @@ -545,28 +688,37 @@ Assign an email address to a subaccount. User will receive an email with confirm ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.AccountManagementApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -AccountManagementApi apiInstance = new AccountManagementApi(); -Integer sid = 56; // Integer | The user id for the subaccount -String email = subaccount_1@email.com; // String | The email address for the subaccount -try { - Object result = apiInstance.privateSetEmailForSubaccountGet(sid, email); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling AccountManagementApi#privateSetEmailForSubaccountGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AccountManagementApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + AccountManagementApi apiInstance = new AccountManagementApi(defaultClient); + Integer sid = 56; // Integer | The user id for the subaccount + String email = subaccount_1@email.com; // String | The email address for the subaccount + try { + Object result = apiInstance.privateSetEmailForSubaccountGet(sid, email); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AccountManagementApi#privateSetEmailForSubaccountGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -590,6 +742,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateSetEmailLanguageGet** > Object privateSetEmailLanguageGet(language) @@ -599,27 +756,36 @@ Changes the language to be used for emails. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.AccountManagementApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -AccountManagementApi apiInstance = new AccountManagementApi(); -String language = en; // String | The abbreviated language name. Valid values include `\"en\"`, `\"ko\"`, `\"zh\"` -try { - Object result = apiInstance.privateSetEmailLanguageGet(language); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling AccountManagementApi#privateSetEmailLanguageGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AccountManagementApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + AccountManagementApi apiInstance = new AccountManagementApi(defaultClient); + String language = en; // String | The abbreviated language name. Valid values include `\"en\"`, `\"ko\"`, `\"zh\"` + try { + Object result = apiInstance.privateSetEmailLanguageGet(language); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AccountManagementApi#privateSetEmailLanguageGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -642,6 +808,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateSetPasswordForSubaccountGet** > Object privateSetPasswordForSubaccountGet(sid, password) @@ -651,28 +822,37 @@ Set the password for the subaccount ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.AccountManagementApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -AccountManagementApi apiInstance = new AccountManagementApi(); -Integer sid = 56; // Integer | The user id for the subaccount -String password = "password_example"; // String | The password for the subaccount -try { - Object result = apiInstance.privateSetPasswordForSubaccountGet(sid, password); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling AccountManagementApi#privateSetPasswordForSubaccountGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AccountManagementApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + AccountManagementApi apiInstance = new AccountManagementApi(defaultClient); + Integer sid = 56; // Integer | The user id for the subaccount + String password = "password_example"; // String | The password for the subaccount + try { + Object result = apiInstance.privateSetPasswordForSubaccountGet(sid, password); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AccountManagementApi#privateSetPasswordForSubaccountGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -696,6 +876,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateToggleNotificationsFromSubaccountGet** > Object privateToggleNotificationsFromSubaccountGet(sid, state) @@ -705,28 +890,37 @@ Enable or disable sending of notifications for the subaccount. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.AccountManagementApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -AccountManagementApi apiInstance = new AccountManagementApi(); -Integer sid = 56; // Integer | The user id for the subaccount -Boolean state = true; // Boolean | enable (`true`) or disable (`false`) notifications -try { - Object result = apiInstance.privateToggleNotificationsFromSubaccountGet(sid, state); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling AccountManagementApi#privateToggleNotificationsFromSubaccountGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AccountManagementApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + AccountManagementApi apiInstance = new AccountManagementApi(defaultClient); + Integer sid = 56; // Integer | The user id for the subaccount + Boolean state = true; // Boolean | enable (`true`) or disable (`false`) notifications + try { + Object result = apiInstance.privateToggleNotificationsFromSubaccountGet(sid, state); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AccountManagementApi#privateToggleNotificationsFromSubaccountGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -750,6 +944,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateToggleSubaccountLoginGet** > Object privateToggleSubaccountLoginGet(sid, state) @@ -759,28 +958,37 @@ Enable or disable login for a subaccount. If login is disabled and a session for ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.AccountManagementApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -AccountManagementApi apiInstance = new AccountManagementApi(); -Integer sid = 56; // Integer | The user id for the subaccount -String state = "state_example"; // String | enable or disable login. -try { - Object result = apiInstance.privateToggleSubaccountLoginGet(sid, state); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling AccountManagementApi#privateToggleSubaccountLoginGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AccountManagementApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + AccountManagementApi apiInstance = new AccountManagementApi(defaultClient); + Integer sid = 56; // Integer | The user id for the subaccount + String state = "state_example"; // String | enable or disable login. + try { + Object result = apiInstance.privateToggleSubaccountLoginGet(sid, state); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AccountManagementApi#privateToggleSubaccountLoginGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -804,6 +1012,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **publicGetAnnouncementsGet** > Object publicGetAnnouncementsGet() @@ -813,26 +1026,35 @@ Retrieves announcements from the last 30 days. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.AccountManagementApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -AccountManagementApi apiInstance = new AccountManagementApi(); -try { - Object result = apiInstance.publicGetAnnouncementsGet(); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling AccountManagementApi#publicGetAnnouncementsGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AccountManagementApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + AccountManagementApi apiInstance = new AccountManagementApi(defaultClient); + try { + Object result = apiInstance.publicGetAnnouncementsGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AccountManagementApi#publicGetAnnouncementsGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -852,3 +1074,8 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + diff --git a/java/docs/AuthenticationApi.md b/java/docs/AuthenticationApi.md index 3affa6f..3871c5f 100644 --- a/java/docs/AuthenticationApi.md +++ b/java/docs/AuthenticationApi.md @@ -18,37 +18,46 @@ Retrieve an Oauth access token, to be used for authentication of 'private ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.AuthenticationApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -AuthenticationApi apiInstance = new AuthenticationApi(); -String grantType = "grantType_example"; // String | Method of authentication -String username = your_email@mail.com; // String | Required for grant type `password` -String password = your_password; // String | Required for grant type `password` -String clientId = "clientId_example"; // String | Required for grant type `client_credentials` and `client_signature` -String clientSecret = "clientSecret_example"; // String | Required for grant type `client_credentials` -String refreshToken = "refreshToken_example"; // String | Required for grant type `refresh_token` -String timestamp = "timestamp_example"; // String | Required for grant type `client_signature`, provides time when request has been generated -String signature = "signature_example"; // String | Required for grant type `client_signature`; it's a cryptographic signature calculated over provided fields using user **secret key**. The signature should be calculated as an HMAC (Hash-based Message Authentication Code) with `SHA256` hash algorithm -String nonce = "nonce_example"; // String | Optional for grant type `client_signature`; delivers user generated initialization vector for the server token -String state = "state_example"; // String | Will be passed back in the response -String scope = connection; // String | Describes type of the access for assigned token, possible values: `connection`, `session`, `session:name`, `trade:[read, read_write, none]`, `wallet:[read, read_write, none]`, `account:[read, read_write, none]`, `expires:NUMBER` (token will expire after `NUMBER` of seconds).

**NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read``` -try { - Object result = apiInstance.publicAuthGet(grantType, username, password, clientId, clientSecret, refreshToken, timestamp, signature, nonce, state, scope); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling AuthenticationApi#publicAuthGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AuthenticationApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + AuthenticationApi apiInstance = new AuthenticationApi(defaultClient); + String grantType = "grantType_example"; // String | Method of authentication + String username = your_email@mail.com; // String | Required for grant type `password` + String password = your_password; // String | Required for grant type `password` + String clientId = "clientId_example"; // String | Required for grant type `client_credentials` and `client_signature` + String clientSecret = "clientSecret_example"; // String | Required for grant type `client_credentials` + String refreshToken = "refreshToken_example"; // String | Required for grant type `refresh_token` + String timestamp = "timestamp_example"; // String | Required for grant type `client_signature`, provides time when request has been generated + String signature = "signature_example"; // String | Required for grant type `client_signature`; it's a cryptographic signature calculated over provided fields using user **secret key**. The signature should be calculated as an HMAC (Hash-based Message Authentication Code) with `SHA256` hash algorithm + String nonce = "nonce_example"; // String | Optional for grant type `client_signature`; delivers user generated initialization vector for the server token + String state = "state_example"; // String | Will be passed back in the response + String scope = connection; // String | Describes type of the access for assigned token, possible values: `connection`, `session`, `session:name`, `trade:[read, read_write, none]`, `wallet:[read, read_write, none]`, `account:[read, read_write, none]`, `expires:NUMBER` (token will expire after `NUMBER` of seconds).

**NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read``` + try { + Object result = apiInstance.publicAuthGet(grantType, username, password, clientId, clientSecret, refreshToken, timestamp, signature, nonce, state, scope); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AuthenticationApi#publicAuthGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -81,3 +90,9 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | +**429** | over limit | - | + diff --git a/java/docs/InternalApi.md b/java/docs/InternalApi.md index d76dd91..80e0198 100644 --- a/java/docs/InternalApi.md +++ b/java/docs/InternalApi.md @@ -25,31 +25,40 @@ Adds new entry to address book of given type ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.InternalApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -InternalApi apiInstance = new InternalApi(); -String currency = "currency_example"; // String | The currency symbol -String type = "type_example"; // String | Address book type -String address = "address_example"; // String | Address in currency format, it must be in address book -String name = Main address; // String | Name of address book entry -String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account -try { - Object result = apiInstance.privateAddToAddressBookGet(currency, type, address, name, tfa); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling InternalApi#privateAddToAddressBookGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.InternalApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + InternalApi apiInstance = new InternalApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String type = "type_example"; // String | Address book type + String address = "address_example"; // String | Address in currency format, it must be in address book + String name = Main address; // String | Name of address book entry + String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account + try { + Object result = apiInstance.privateAddToAddressBookGet(currency, type, address, name, tfa); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling InternalApi#privateAddToAddressBookGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -76,6 +85,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateDisableTfaWithRecoveryCodeGet** > Object privateDisableTfaWithRecoveryCodeGet(password, code) @@ -85,28 +99,37 @@ Disables TFA with one time recovery code ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.InternalApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -InternalApi apiInstance = new InternalApi(); -String password = "password_example"; // String | The password for the subaccount -String code = "code_example"; // String | One time recovery code -try { - Object result = apiInstance.privateDisableTfaWithRecoveryCodeGet(password, code); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling InternalApi#privateDisableTfaWithRecoveryCodeGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.InternalApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + InternalApi apiInstance = new InternalApi(defaultClient); + String password = "password_example"; // String | The password for the subaccount + String code = "code_example"; // String | One time recovery code + try { + Object result = apiInstance.privateDisableTfaWithRecoveryCodeGet(password, code); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling InternalApi#privateDisableTfaWithRecoveryCodeGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -130,6 +153,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateGetAddressBookGet** > Object privateGetAddressBookGet(currency, type) @@ -139,28 +167,37 @@ Retrieves address book of given type ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.InternalApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -InternalApi apiInstance = new InternalApi(); -String currency = "currency_example"; // String | The currency symbol -String type = "type_example"; // String | Address book type -try { - Object result = apiInstance.privateGetAddressBookGet(currency, type); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling InternalApi#privateGetAddressBookGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.InternalApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + InternalApi apiInstance = new InternalApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String type = "type_example"; // String | Address book type + try { + Object result = apiInstance.privateGetAddressBookGet(currency, type); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling InternalApi#privateGetAddressBookGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -184,6 +221,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateRemoveFromAddressBookGet** > Object privateRemoveFromAddressBookGet(currency, type, address, tfa) @@ -193,30 +235,39 @@ Adds new entry to address book of given type ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.InternalApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -InternalApi apiInstance = new InternalApi(); -String currency = "currency_example"; // String | The currency symbol -String type = "type_example"; // String | Address book type -String address = "address_example"; // String | Address in currency format, it must be in address book -String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account -try { - Object result = apiInstance.privateRemoveFromAddressBookGet(currency, type, address, tfa); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling InternalApi#privateRemoveFromAddressBookGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.InternalApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + InternalApi apiInstance = new InternalApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String type = "type_example"; // String | Address book type + String address = "address_example"; // String | Address in currency format, it must be in address book + String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account + try { + Object result = apiInstance.privateRemoveFromAddressBookGet(currency, type, address, tfa); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling InternalApi#privateRemoveFromAddressBookGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -242,6 +293,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateSubmitTransferToSubaccountGet** > Object privateSubmitTransferToSubaccountGet(currency, amount, destination) @@ -251,29 +307,38 @@ Transfer funds to a subaccount. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.InternalApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -InternalApi apiInstance = new InternalApi(); -String currency = "currency_example"; // String | The currency symbol -BigDecimal amount = new BigDecimal(); // BigDecimal | Amount of funds to be transferred -Integer destination = 1; // Integer | Id of destination subaccount -try { - Object result = apiInstance.privateSubmitTransferToSubaccountGet(currency, amount, destination); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling InternalApi#privateSubmitTransferToSubaccountGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.InternalApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + InternalApi apiInstance = new InternalApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + BigDecimal amount = new BigDecimal(); // BigDecimal | Amount of funds to be transferred + Integer destination = 1; // Integer | Id of destination subaccount + try { + Object result = apiInstance.privateSubmitTransferToSubaccountGet(currency, amount, destination); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling InternalApi#privateSubmitTransferToSubaccountGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -298,6 +363,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateSubmitTransferToUserGet** > Object privateSubmitTransferToUserGet(currency, amount, destination, tfa) @@ -307,30 +377,39 @@ Transfer funds to a another user. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.InternalApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -InternalApi apiInstance = new InternalApi(); -String currency = "currency_example"; // String | The currency symbol -BigDecimal amount = new BigDecimal(); // BigDecimal | Amount of funds to be transferred -String destination = "destination_example"; // String | Destination address from address book -String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account -try { - Object result = apiInstance.privateSubmitTransferToUserGet(currency, amount, destination, tfa); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling InternalApi#privateSubmitTransferToUserGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.InternalApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + InternalApi apiInstance = new InternalApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + BigDecimal amount = new BigDecimal(); // BigDecimal | Amount of funds to be transferred + String destination = "destination_example"; // String | Destination address from address book + String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account + try { + Object result = apiInstance.privateSubmitTransferToUserGet(currency, amount, destination, tfa); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling InternalApi#privateSubmitTransferToUserGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -356,6 +435,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateToggleDepositAddressCreationGet** > Object privateToggleDepositAddressCreationGet(currency, state) @@ -365,28 +449,37 @@ Enable or disable deposit address creation ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.InternalApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -InternalApi apiInstance = new InternalApi(); -String currency = "currency_example"; // String | The currency symbol -Boolean state = true; // Boolean | -try { - Object result = apiInstance.privateToggleDepositAddressCreationGet(currency, state); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling InternalApi#privateToggleDepositAddressCreationGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.InternalApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + InternalApi apiInstance = new InternalApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + Boolean state = true; // Boolean | + try { + Object result = apiInstance.privateToggleDepositAddressCreationGet(currency, state); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling InternalApi#privateToggleDepositAddressCreationGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -410,6 +503,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetFooterGet** > Object publicGetFooterGet() @@ -419,26 +517,35 @@ Get information to be displayed in the footer of the website. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.InternalApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -InternalApi apiInstance = new InternalApi(); -try { - Object result = apiInstance.publicGetFooterGet(); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling InternalApi#publicGetFooterGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.InternalApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + InternalApi apiInstance = new InternalApi(defaultClient); + try { + Object result = apiInstance.publicGetFooterGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling InternalApi#publicGetFooterGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -458,6 +565,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **publicGetOptionMarkPricesGet** > Object publicGetOptionMarkPricesGet(currency) @@ -467,27 +579,36 @@ Retrives market prices and its implied volatility of options instruments ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.InternalApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -InternalApi apiInstance = new InternalApi(); -String currency = "currency_example"; // String | The currency symbol -try { - Object result = apiInstance.publicGetOptionMarkPricesGet(currency); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling InternalApi#publicGetOptionMarkPricesGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.InternalApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + InternalApi apiInstance = new InternalApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + try { + Object result = apiInstance.publicGetOptionMarkPricesGet(currency); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling InternalApi#publicGetOptionMarkPricesGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -510,6 +631,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **publicValidateFieldGet** > Object publicValidateFieldGet(field, value, value2) @@ -519,29 +645,38 @@ Method used to introduce the client software connected to Deribit platform over ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.InternalApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -InternalApi apiInstance = new InternalApi(); -String field = "field_example"; // String | Name of the field to be validated, examples: postal_code, date_of_birth -String value = "value_example"; // String | Value to be checked -String value2 = "value2_example"; // String | Additional value to be compared with -try { - Object result = apiInstance.publicValidateFieldGet(field, value, value2); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling InternalApi#publicValidateFieldGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.InternalApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + InternalApi apiInstance = new InternalApi(defaultClient); + String field = "field_example"; // String | Name of the field to be validated, examples: postal_code, date_of_birth + String value = "value_example"; // String | Value to be checked + String value2 = "value2_example"; // String | Additional value to be compared with + try { + Object result = apiInstance.publicValidateFieldGet(field, value, value2); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling InternalApi#publicValidateFieldGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -566,3 +701,8 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + diff --git a/java/docs/MarketDataApi.md b/java/docs/MarketDataApi.md index dadd5b0..e30f36e 100644 --- a/java/docs/MarketDataApi.md +++ b/java/docs/MarketDataApi.md @@ -33,28 +33,37 @@ Retrieves the summary information such as open interest, 24h volume, etc. for al ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.MarketDataApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -MarketDataApi apiInstance = new MarketDataApi(); -String currency = "currency_example"; // String | The currency symbol -String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered -try { - Object result = apiInstance.publicGetBookSummaryByCurrencyGet(currency, kind); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling MarketDataApi#publicGetBookSummaryByCurrencyGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.MarketDataApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + MarketDataApi apiInstance = new MarketDataApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered + try { + Object result = apiInstance.publicGetBookSummaryByCurrencyGet(currency, kind); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling MarketDataApi#publicGetBookSummaryByCurrencyGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -78,6 +87,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetBookSummaryByInstrumentGet** > Object publicGetBookSummaryByInstrumentGet(instrumentName) @@ -87,27 +101,36 @@ Retrieves the summary information such as open interest, 24h volume, etc. for a ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.MarketDataApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -MarketDataApi apiInstance = new MarketDataApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -try { - Object result = apiInstance.publicGetBookSummaryByInstrumentGet(instrumentName); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling MarketDataApi#publicGetBookSummaryByInstrumentGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.MarketDataApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + MarketDataApi apiInstance = new MarketDataApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + try { + Object result = apiInstance.publicGetBookSummaryByInstrumentGet(instrumentName); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling MarketDataApi#publicGetBookSummaryByInstrumentGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -130,6 +153,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetContractSizeGet** > Object publicGetContractSizeGet(instrumentName) @@ -139,27 +167,36 @@ Retrieves contract size of provided instrument. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.MarketDataApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -MarketDataApi apiInstance = new MarketDataApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -try { - Object result = apiInstance.publicGetContractSizeGet(instrumentName); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling MarketDataApi#publicGetContractSizeGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.MarketDataApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + MarketDataApi apiInstance = new MarketDataApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + try { + Object result = apiInstance.publicGetContractSizeGet(instrumentName); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling MarketDataApi#publicGetContractSizeGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -182,6 +219,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **publicGetCurrenciesGet** > Object publicGetCurrenciesGet() @@ -191,26 +233,35 @@ Retrieves all cryptocurrencies supported by the API. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.MarketDataApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -MarketDataApi apiInstance = new MarketDataApi(); -try { - Object result = apiInstance.publicGetCurrenciesGet(); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling MarketDataApi#publicGetCurrenciesGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.MarketDataApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + MarketDataApi apiInstance = new MarketDataApi(defaultClient); + try { + Object result = apiInstance.publicGetCurrenciesGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling MarketDataApi#publicGetCurrenciesGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -230,6 +281,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **publicGetFundingChartDataGet** > Object publicGetFundingChartDataGet(instrumentName, length) @@ -239,28 +295,37 @@ Retrieve the latest user trades that have occurred for PERPETUAL instruments in ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.MarketDataApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -MarketDataApi apiInstance = new MarketDataApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -String length = "length_example"; // String | Specifies time period. `8h` - 8 hours, `24h` - 24 hours -try { - Object result = apiInstance.publicGetFundingChartDataGet(instrumentName, length); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling MarketDataApi#publicGetFundingChartDataGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.MarketDataApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + MarketDataApi apiInstance = new MarketDataApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + String length = "length_example"; // String | Specifies time period. `8h` - 8 hours, `24h` - 24 hours + try { + Object result = apiInstance.publicGetFundingChartDataGet(instrumentName, length); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling MarketDataApi#publicGetFundingChartDataGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -284,6 +349,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetHistoricalVolatilityGet** > Object publicGetHistoricalVolatilityGet(currency) @@ -293,27 +363,36 @@ Provides information about historical volatility for given cryptocurrency. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.MarketDataApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -MarketDataApi apiInstance = new MarketDataApi(); -String currency = "currency_example"; // String | The currency symbol -try { - Object result = apiInstance.publicGetHistoricalVolatilityGet(currency); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling MarketDataApi#publicGetHistoricalVolatilityGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.MarketDataApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + MarketDataApi apiInstance = new MarketDataApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + try { + Object result = apiInstance.publicGetHistoricalVolatilityGet(currency); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling MarketDataApi#publicGetHistoricalVolatilityGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -336,6 +415,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **publicGetIndexGet** > Object publicGetIndexGet(currency) @@ -345,27 +429,36 @@ Retrieves the current index price for the instruments, for the selected currency ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.MarketDataApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -MarketDataApi apiInstance = new MarketDataApi(); -String currency = "currency_example"; // String | The currency symbol -try { - Object result = apiInstance.publicGetIndexGet(currency); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling MarketDataApi#publicGetIndexGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.MarketDataApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + MarketDataApi apiInstance = new MarketDataApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + try { + Object result = apiInstance.publicGetIndexGet(currency); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling MarketDataApi#publicGetIndexGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -388,6 +481,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetInstrumentsGet** > Object publicGetInstrumentsGet(currency, kind, expired) @@ -397,29 +495,38 @@ Retrieves available trading instruments. This method can be used to see which in ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.MarketDataApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -MarketDataApi apiInstance = new MarketDataApi(); -String currency = "currency_example"; // String | The currency symbol -String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered -Boolean expired = false; // Boolean | Set to true to show expired instruments instead of active ones. -try { - Object result = apiInstance.publicGetInstrumentsGet(currency, kind, expired); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling MarketDataApi#publicGetInstrumentsGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.MarketDataApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + MarketDataApi apiInstance = new MarketDataApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered + Boolean expired = false; // Boolean | Set to true to show expired instruments instead of active ones. + try { + Object result = apiInstance.publicGetInstrumentsGet(currency, kind, expired); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling MarketDataApi#publicGetInstrumentsGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -444,6 +551,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **publicGetLastSettlementsByCurrencyGet** > Object publicGetLastSettlementsByCurrencyGet(currency, type, count, continuation, searchStartTimestamp) @@ -453,31 +565,40 @@ Retrieves historical settlement, delivery and bankruptcy events coming from all ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.MarketDataApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -MarketDataApi apiInstance = new MarketDataApi(); -String currency = "currency_example"; // String | The currency symbol -String type = "type_example"; // String | Settlement type -Integer count = 56; // Integer | Number of requested items, default - `20` -String continuation = xY7T6cutS3t2B9YtaDkE6TS379oKnkzTvmEDUnEUP2Msa9xKWNNaT; // String | Continuation token for pagination -Integer searchStartTimestamp = 1536569522277; // Integer | The latest timestamp to return result for -try { - Object result = apiInstance.publicGetLastSettlementsByCurrencyGet(currency, type, count, continuation, searchStartTimestamp); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling MarketDataApi#publicGetLastSettlementsByCurrencyGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.MarketDataApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + MarketDataApi apiInstance = new MarketDataApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String type = "type_example"; // String | Settlement type + Integer count = 56; // Integer | Number of requested items, default - `20` + String continuation = xY7T6cutS3t2B9YtaDkE6TS379oKnkzTvmEDUnEUP2Msa9xKWNNaT; // String | Continuation token for pagination + Integer searchStartTimestamp = 1536569522277; // Integer | The latest timestamp to return result for + try { + Object result = apiInstance.publicGetLastSettlementsByCurrencyGet(currency, type, count, continuation, searchStartTimestamp); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling MarketDataApi#publicGetLastSettlementsByCurrencyGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -504,6 +625,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetLastSettlementsByInstrumentGet** > Object publicGetLastSettlementsByInstrumentGet(instrumentName, type, count, continuation, searchStartTimestamp) @@ -513,31 +639,40 @@ Retrieves historical public settlement, delivery and bankruptcy events filtered ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.MarketDataApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -MarketDataApi apiInstance = new MarketDataApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -String type = "type_example"; // String | Settlement type -Integer count = 56; // Integer | Number of requested items, default - `20` -String continuation = xY7T6cutS3t2B9YtaDkE6TS379oKnkzTvmEDUnEUP2Msa9xKWNNaT; // String | Continuation token for pagination -Integer searchStartTimestamp = 1536569522277; // Integer | The latest timestamp to return result for -try { - Object result = apiInstance.publicGetLastSettlementsByInstrumentGet(instrumentName, type, count, continuation, searchStartTimestamp); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling MarketDataApi#publicGetLastSettlementsByInstrumentGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.MarketDataApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + MarketDataApi apiInstance = new MarketDataApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + String type = "type_example"; // String | Settlement type + Integer count = 56; // Integer | Number of requested items, default - `20` + String continuation = xY7T6cutS3t2B9YtaDkE6TS379oKnkzTvmEDUnEUP2Msa9xKWNNaT; // String | Continuation token for pagination + Integer searchStartTimestamp = 1536569522277; // Integer | The latest timestamp to return result for + try { + Object result = apiInstance.publicGetLastSettlementsByInstrumentGet(instrumentName, type, count, continuation, searchStartTimestamp); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling MarketDataApi#publicGetLastSettlementsByInstrumentGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -564,6 +699,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetLastTradesByCurrencyAndTimeGet** > Object publicGetLastTradesByCurrencyAndTimeGet(currency, startTimestamp, endTimestamp, kind, count, includeOld, sorting) @@ -573,33 +713,42 @@ Retrieve the latest trades that have occurred for instruments in a specific curr ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.MarketDataApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -MarketDataApi apiInstance = new MarketDataApi(); -String currency = "currency_example"; // String | The currency symbol -Integer startTimestamp = 1536569522277; // Integer | The earliest timestamp to return result for -Integer endTimestamp = 1536569522277; // Integer | The most recent timestamp to return result for -String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered -Integer count = 56; // Integer | Number of requested items, default - `10` -Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` -String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) -try { - Object result = apiInstance.publicGetLastTradesByCurrencyAndTimeGet(currency, startTimestamp, endTimestamp, kind, count, includeOld, sorting); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling MarketDataApi#publicGetLastTradesByCurrencyAndTimeGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.MarketDataApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + MarketDataApi apiInstance = new MarketDataApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + Integer startTimestamp = 1536569522277; // Integer | The earliest timestamp to return result for + Integer endTimestamp = 1536569522277; // Integer | The most recent timestamp to return result for + String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered + Integer count = 56; // Integer | Number of requested items, default - `10` + Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` + String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + try { + Object result = apiInstance.publicGetLastTradesByCurrencyAndTimeGet(currency, startTimestamp, endTimestamp, kind, count, includeOld, sorting); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling MarketDataApi#publicGetLastTradesByCurrencyAndTimeGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -628,6 +777,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetLastTradesByCurrencyGet** > Object publicGetLastTradesByCurrencyGet(currency, kind, startId, endId, count, includeOld, sorting) @@ -637,33 +791,42 @@ Retrieve the latest trades that have occurred for instruments in a specific curr ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.MarketDataApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -MarketDataApi apiInstance = new MarketDataApi(); -String currency = "currency_example"; // String | The currency symbol -String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered -String startId = "startId_example"; // String | The ID number of the first trade to be returned -String endId = "endId_example"; // String | The ID number of the last trade to be returned -Integer count = 56; // Integer | Number of requested items, default - `10` -Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` -String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) -try { - Object result = apiInstance.publicGetLastTradesByCurrencyGet(currency, kind, startId, endId, count, includeOld, sorting); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling MarketDataApi#publicGetLastTradesByCurrencyGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.MarketDataApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + MarketDataApi apiInstance = new MarketDataApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered + String startId = "startId_example"; // String | The ID number of the first trade to be returned + String endId = "endId_example"; // String | The ID number of the last trade to be returned + Integer count = 56; // Integer | Number of requested items, default - `10` + Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` + String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + try { + Object result = apiInstance.publicGetLastTradesByCurrencyGet(currency, kind, startId, endId, count, includeOld, sorting); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling MarketDataApi#publicGetLastTradesByCurrencyGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -692,6 +855,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetLastTradesByInstrumentAndTimeGet** > Object publicGetLastTradesByInstrumentAndTimeGet(instrumentName, startTimestamp, endTimestamp, count, includeOld, sorting) @@ -701,32 +869,41 @@ Retrieve the latest trades that have occurred for a specific instrument and with ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.MarketDataApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -MarketDataApi apiInstance = new MarketDataApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -Integer startTimestamp = 1536569522277; // Integer | The earliest timestamp to return result for -Integer endTimestamp = 1536569522277; // Integer | The most recent timestamp to return result for -Integer count = 56; // Integer | Number of requested items, default - `10` -Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` -String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) -try { - Object result = apiInstance.publicGetLastTradesByInstrumentAndTimeGet(instrumentName, startTimestamp, endTimestamp, count, includeOld, sorting); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling MarketDataApi#publicGetLastTradesByInstrumentAndTimeGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.MarketDataApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + MarketDataApi apiInstance = new MarketDataApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + Integer startTimestamp = 1536569522277; // Integer | The earliest timestamp to return result for + Integer endTimestamp = 1536569522277; // Integer | The most recent timestamp to return result for + Integer count = 56; // Integer | Number of requested items, default - `10` + Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` + String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + try { + Object result = apiInstance.publicGetLastTradesByInstrumentAndTimeGet(instrumentName, startTimestamp, endTimestamp, count, includeOld, sorting); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling MarketDataApi#publicGetLastTradesByInstrumentAndTimeGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -754,6 +931,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetLastTradesByInstrumentGet** > Object publicGetLastTradesByInstrumentGet(instrumentName, startSeq, endSeq, count, includeOld, sorting) @@ -763,32 +945,41 @@ Retrieve the latest trades that have occurred for a specific instrument. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.MarketDataApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -MarketDataApi apiInstance = new MarketDataApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -Integer startSeq = 56; // Integer | The sequence number of the first trade to be returned -Integer endSeq = 56; // Integer | The sequence number of the last trade to be returned -Integer count = 56; // Integer | Number of requested items, default - `10` -Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` -String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) -try { - Object result = apiInstance.publicGetLastTradesByInstrumentGet(instrumentName, startSeq, endSeq, count, includeOld, sorting); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling MarketDataApi#publicGetLastTradesByInstrumentGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.MarketDataApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + MarketDataApi apiInstance = new MarketDataApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + Integer startSeq = 56; // Integer | The sequence number of the first trade to be returned + Integer endSeq = 56; // Integer | The sequence number of the last trade to be returned + Integer count = 56; // Integer | Number of requested items, default - `10` + Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` + String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + try { + Object result = apiInstance.publicGetLastTradesByInstrumentGet(instrumentName, startSeq, endSeq, count, includeOld, sorting); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling MarketDataApi#publicGetLastTradesByInstrumentGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -816,6 +1007,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetOrderBookGet** > Object publicGetOrderBookGet(instrumentName, depth) @@ -825,28 +1021,37 @@ Retrieves the order book, along with other market values for a given instrument. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.MarketDataApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -MarketDataApi apiInstance = new MarketDataApi(); -String instrumentName = "instrumentName_example"; // String | The instrument name for which to retrieve the order book, see [`getinstruments`](#getinstruments) to obtain instrument names. -BigDecimal depth = new BigDecimal(); // BigDecimal | The number of entries to return for bids and asks. -try { - Object result = apiInstance.publicGetOrderBookGet(instrumentName, depth); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling MarketDataApi#publicGetOrderBookGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.MarketDataApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + MarketDataApi apiInstance = new MarketDataApi(defaultClient); + String instrumentName = "instrumentName_example"; // String | The instrument name for which to retrieve the order book, see [`getinstruments`](#getinstruments) to obtain instrument names. + BigDecimal depth = new BigDecimal(); // BigDecimal | The number of entries to return for bids and asks. + try { + Object result = apiInstance.publicGetOrderBookGet(instrumentName, depth); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling MarketDataApi#publicGetOrderBookGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -870,6 +1075,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetTradeVolumesGet** > Object publicGetTradeVolumesGet() @@ -879,26 +1089,35 @@ Retrieves aggregated 24h trade volumes for different instrument types and curren ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.MarketDataApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -MarketDataApi apiInstance = new MarketDataApi(); -try { - Object result = apiInstance.publicGetTradeVolumesGet(); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling MarketDataApi#publicGetTradeVolumesGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.MarketDataApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + MarketDataApi apiInstance = new MarketDataApi(defaultClient); + try { + Object result = apiInstance.publicGetTradeVolumesGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling MarketDataApi#publicGetTradeVolumesGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -918,6 +1137,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetTradingviewChartDataGet** > Object publicGetTradingviewChartDataGet(instrumentName, startTimestamp, endTimestamp) @@ -927,29 +1151,38 @@ Publicly available market data used to generate a TradingView candle chart. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.MarketDataApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -MarketDataApi apiInstance = new MarketDataApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -Integer startTimestamp = 1536569522277; // Integer | The earliest timestamp to return result for -Integer endTimestamp = 1536569522277; // Integer | The most recent timestamp to return result for -try { - Object result = apiInstance.publicGetTradingviewChartDataGet(instrumentName, startTimestamp, endTimestamp); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling MarketDataApi#publicGetTradingviewChartDataGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.MarketDataApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + MarketDataApi apiInstance = new MarketDataApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + Integer startTimestamp = 1536569522277; // Integer | The earliest timestamp to return result for + Integer endTimestamp = 1536569522277; // Integer | The most recent timestamp to return result for + try { + Object result = apiInstance.publicGetTradingviewChartDataGet(instrumentName, startTimestamp, endTimestamp); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling MarketDataApi#publicGetTradingviewChartDataGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -974,6 +1207,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicTickerGet** > Object publicTickerGet(instrumentName) @@ -983,27 +1221,36 @@ Get ticker for an instrument. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.MarketDataApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -MarketDataApi apiInstance = new MarketDataApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -try { - Object result = apiInstance.publicTickerGet(instrumentName); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling MarketDataApi#publicTickerGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.MarketDataApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + MarketDataApi apiInstance = new MarketDataApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + try { + Object result = apiInstance.publicTickerGet(instrumentName); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling MarketDataApi#publicTickerGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1026,3 +1273,8 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + diff --git a/java/docs/PrivateApi.md b/java/docs/PrivateApi.md index 86dc586..755856a 100644 --- a/java/docs/PrivateApi.md +++ b/java/docs/PrivateApi.md @@ -67,31 +67,40 @@ Adds new entry to address book of given type ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String currency = "currency_example"; // String | The currency symbol -String type = "type_example"; // String | Address book type -String address = "address_example"; // String | Address in currency format, it must be in address book -String name = Main address; // String | Name of address book entry -String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account -try { - Object result = apiInstance.privateAddToAddressBookGet(currency, type, address, name, tfa); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateAddToAddressBookGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String type = "type_example"; // String | Address book type + String address = "address_example"; // String | Address in currency format, it must be in address book + String name = Main address; // String | Name of address book entry + String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account + try { + Object result = apiInstance.privateAddToAddressBookGet(currency, type, address, name, tfa); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateAddToAddressBookGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -118,6 +127,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateBuyGet** > Object privateBuyGet(instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced) @@ -127,38 +141,47 @@ Places a buy order for an instrument. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -BigDecimal amount = new BigDecimal(); // BigDecimal | It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH -String type = "type_example"; // String | The order type, default: `\"limit\"` -String label = "label_example"; // String | user defined label for the order (maximum 32 characters) -BigDecimal price = new BigDecimal(); // BigDecimal |

The order price in base currency (Only for limit and stop_limit orders)

When adding order with advanced=usd, the field price should be the option price value in USD.

When adding order with advanced=implv, the field price should be a value of implied volatility in percentages. For example, price=100, means implied volatility of 100%

-String timeInForce = "good_til_cancelled"; // String |

Specifies how long the order remains in effect. Default `\"good_til_cancelled\"`

  • `\"good_til_cancelled\"` - unfilled order remains in order book until cancelled
  • `\"fill_or_kill\"` - execute a transaction immediately and completely or not at all
  • `\"immediate_or_cancel\"` - execute a transaction immediately, and any portion of the order that cannot be immediately filled is cancelled
-BigDecimal maxShow = new BigDecimal(); // BigDecimal | Maximum amount within an order to be shown to other customers, `0` for invisible order -Boolean postOnly = true; // Boolean |

If true, the order is considered post-only. If the new price would cause the order to be filled immediately (as taker), the price will be changed to be just below the bid.

Only valid in combination with time_in_force=`\"good_til_cancelled\"`

-Boolean reduceOnly = false; // Boolean | If `true`, the order is considered reduce-only which is intended to only reduce a current position -BigDecimal stopPrice = new BigDecimal(); // BigDecimal | Stop price, required for stop limit orders (Only for stop orders) -String trigger = "trigger_example"; // String | Defines trigger type, required for `\"stop_limit\"` order type -String advanced = "advanced_example"; // String | Advanced option order type. (Only for options) -try { - Object result = apiInstance.privateBuyGet(instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateBuyGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + BigDecimal amount = new BigDecimal(); // BigDecimal | It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH + String type = "type_example"; // String | The order type, default: `\"limit\"` + String label = "label_example"; // String | user defined label for the order (maximum 32 characters) + BigDecimal price = new BigDecimal(); // BigDecimal |

The order price in base currency (Only for limit and stop_limit orders)

When adding order with advanced=usd, the field price should be the option price value in USD.

When adding order with advanced=implv, the field price should be a value of implied volatility in percentages. For example, price=100, means implied volatility of 100%

+ String timeInForce = "good_til_cancelled"; // String |

Specifies how long the order remains in effect. Default `\"good_til_cancelled\"`

  • `\"good_til_cancelled\"` - unfilled order remains in order book until cancelled
  • `\"fill_or_kill\"` - execute a transaction immediately and completely or not at all
  • `\"immediate_or_cancel\"` - execute a transaction immediately, and any portion of the order that cannot be immediately filled is cancelled
+ BigDecimal maxShow = new BigDecimal(); // BigDecimal | Maximum amount within an order to be shown to other customers, `0` for invisible order + Boolean postOnly = true; // Boolean |

If true, the order is considered post-only. If the new price would cause the order to be filled immediately (as taker), the price will be changed to be just below the bid.

Only valid in combination with time_in_force=`\"good_til_cancelled\"`

+ Boolean reduceOnly = false; // Boolean | If `true`, the order is considered reduce-only which is intended to only reduce a current position + BigDecimal stopPrice = new BigDecimal(); // BigDecimal | Stop price, required for stop limit orders (Only for stop orders) + String trigger = "trigger_example"; // String | Defines trigger type, required for `\"stop_limit\"` order type + String advanced = "advanced_example"; // String | Advanced option order type. (Only for options) + try { + Object result = apiInstance.privateBuyGet(instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateBuyGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -192,6 +215,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateCancelAllByCurrencyGet** > Object privateCancelAllByCurrencyGet(currency, kind, type) @@ -201,29 +229,38 @@ Cancels all orders by currency, optionally filtered by instrument kind and/or or ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String currency = "currency_example"; // String | The currency symbol -String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered -String type = "type_example"; // String | Order type - limit, stop or all, default - `all` -try { - Object result = apiInstance.privateCancelAllByCurrencyGet(currency, kind, type); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateCancelAllByCurrencyGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered + String type = "type_example"; // String | Order type - limit, stop or all, default - `all` + try { + Object result = apiInstance.privateCancelAllByCurrencyGet(currency, kind, type); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateCancelAllByCurrencyGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -248,6 +285,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateCancelAllByInstrumentGet** > Object privateCancelAllByInstrumentGet(instrumentName, type) @@ -257,28 +299,37 @@ Cancels all orders by instrument, optionally filtered by order type. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -String type = "type_example"; // String | Order type - limit, stop or all, default - `all` -try { - Object result = apiInstance.privateCancelAllByInstrumentGet(instrumentName, type); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateCancelAllByInstrumentGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + String type = "type_example"; // String | Order type - limit, stop or all, default - `all` + try { + Object result = apiInstance.privateCancelAllByInstrumentGet(instrumentName, type); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateCancelAllByInstrumentGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -302,6 +353,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateCancelAllGet** > Object privateCancelAllGet() @@ -311,26 +367,35 @@ This method cancels all users orders and stop orders within all currencies and i ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -try { - Object result = apiInstance.privateCancelAllGet(); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateCancelAllGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + try { + Object result = apiInstance.privateCancelAllGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateCancelAllGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -350,6 +415,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateCancelGet** > Object privateCancelGet(orderId) @@ -359,27 +429,36 @@ Cancel an order, specified by order id ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String orderId = ETH-100234; // String | The order id -try { - Object result = apiInstance.privateCancelGet(orderId); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateCancelGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String orderId = ETH-100234; // String | The order id + try { + Object result = apiInstance.privateCancelGet(orderId); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateCancelGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -402,6 +481,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateCancelTransferByIdGet** > Object privateCancelTransferByIdGet(currency, id, tfa) @@ -411,29 +495,38 @@ Cancel transfer ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String currency = "currency_example"; // String | The currency symbol -Integer id = 12; // Integer | Id of transfer -String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account -try { - Object result = apiInstance.privateCancelTransferByIdGet(currency, id, tfa); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateCancelTransferByIdGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + Integer id = 12; // Integer | Id of transfer + String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account + try { + Object result = apiInstance.privateCancelTransferByIdGet(currency, id, tfa); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateCancelTransferByIdGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -458,6 +551,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateCancelWithdrawalGet** > Object privateCancelWithdrawalGet(currency, id) @@ -467,28 +565,37 @@ Cancels withdrawal request ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String currency = "currency_example"; // String | The currency symbol -BigDecimal id = 1; // BigDecimal | The withdrawal id -try { - Object result = apiInstance.privateCancelWithdrawalGet(currency, id); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateCancelWithdrawalGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + BigDecimal id = 1; // BigDecimal | The withdrawal id + try { + Object result = apiInstance.privateCancelWithdrawalGet(currency, id); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateCancelWithdrawalGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -512,6 +619,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateChangeSubaccountNameGet** > Object privateChangeSubaccountNameGet(sid, name) @@ -521,28 +633,37 @@ Change the user name for a subaccount ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -Integer sid = 56; // Integer | The user id for the subaccount -String name = newUserName; // String | The new user name -try { - Object result = apiInstance.privateChangeSubaccountNameGet(sid, name); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateChangeSubaccountNameGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + Integer sid = 56; // Integer | The user id for the subaccount + String name = newUserName; // String | The new user name + try { + Object result = apiInstance.privateChangeSubaccountNameGet(sid, name); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateChangeSubaccountNameGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -566,6 +687,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateClosePositionGet** > Object privateClosePositionGet(instrumentName, type, price) @@ -575,29 +701,38 @@ Makes closing position reduce only order . ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -String type = "type_example"; // String | The order type -BigDecimal price = new BigDecimal(); // BigDecimal | Optional price for limit order. -try { - Object result = apiInstance.privateClosePositionGet(instrumentName, type, price); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateClosePositionGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + String type = "type_example"; // String | The order type + BigDecimal price = new BigDecimal(); // BigDecimal | Optional price for limit order. + try { + Object result = apiInstance.privateClosePositionGet(instrumentName, type, price); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateClosePositionGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -622,6 +757,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateCreateDepositAddressGet** > Object privateCreateDepositAddressGet(currency) @@ -631,27 +771,36 @@ Creates deposit address in currency ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String currency = "currency_example"; // String | The currency symbol -try { - Object result = apiInstance.privateCreateDepositAddressGet(currency); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateCreateDepositAddressGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + try { + Object result = apiInstance.privateCreateDepositAddressGet(currency); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateCreateDepositAddressGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -674,6 +823,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateCreateSubaccountGet** > Object privateCreateSubaccountGet() @@ -683,26 +837,35 @@ Create a new subaccount ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -try { - Object result = apiInstance.privateCreateSubaccountGet(); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateCreateSubaccountGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + try { + Object result = apiInstance.privateCreateSubaccountGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateCreateSubaccountGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -722,6 +885,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateDisableTfaForSubaccountGet** > Object privateDisableTfaForSubaccountGet(sid) @@ -731,27 +899,36 @@ Disable two factor authentication for a subaccount. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -Integer sid = 56; // Integer | The user id for the subaccount -try { - Object result = apiInstance.privateDisableTfaForSubaccountGet(sid); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateDisableTfaForSubaccountGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + Integer sid = 56; // Integer | The user id for the subaccount + try { + Object result = apiInstance.privateDisableTfaForSubaccountGet(sid); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateDisableTfaForSubaccountGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -774,6 +951,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateDisableTfaWithRecoveryCodeGet** > Object privateDisableTfaWithRecoveryCodeGet(password, code) @@ -783,28 +965,37 @@ Disables TFA with one time recovery code ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String password = "password_example"; // String | The password for the subaccount -String code = "code_example"; // String | One time recovery code -try { - Object result = apiInstance.privateDisableTfaWithRecoveryCodeGet(password, code); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateDisableTfaWithRecoveryCodeGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String password = "password_example"; // String | The password for the subaccount + String code = "code_example"; // String | One time recovery code + try { + Object result = apiInstance.privateDisableTfaWithRecoveryCodeGet(password, code); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateDisableTfaWithRecoveryCodeGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -828,6 +1019,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateEditGet** > Object privateEditGet(orderId, amount, price, postOnly, advanced, stopPrice) @@ -837,32 +1033,41 @@ Change price, amount and/or other properties of an order. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String orderId = ETH-100234; // String | The order id -BigDecimal amount = new BigDecimal(); // BigDecimal | It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH -BigDecimal price = new BigDecimal(); // BigDecimal |

The order price in base currency.

When editing an option order with advanced=usd, the field price should be the option price value in USD.

When editing an option order with advanced=implv, the field price should be a value of implied volatility in percentages. For example, price=100, means implied volatility of 100%

-Boolean postOnly = true; // Boolean |

If true, the order is considered post-only. If the new price would cause the order to be filled immediately (as taker), the price will be changed to be just below the bid.

Only valid in combination with time_in_force=`\"good_til_cancelled\"`

-String advanced = "advanced_example"; // String | Advanced option order type. If you have posted an advanced option order, it is necessary to re-supply this parameter when editing it (Only for options) -BigDecimal stopPrice = new BigDecimal(); // BigDecimal | Stop price, required for stop limit orders (Only for stop orders) -try { - Object result = apiInstance.privateEditGet(orderId, amount, price, postOnly, advanced, stopPrice); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateEditGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String orderId = ETH-100234; // String | The order id + BigDecimal amount = new BigDecimal(); // BigDecimal | It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH + BigDecimal price = new BigDecimal(); // BigDecimal |

The order price in base currency.

When editing an option order with advanced=usd, the field price should be the option price value in USD.

When editing an option order with advanced=implv, the field price should be a value of implied volatility in percentages. For example, price=100, means implied volatility of 100%

+ Boolean postOnly = true; // Boolean |

If true, the order is considered post-only. If the new price would cause the order to be filled immediately (as taker), the price will be changed to be just below the bid.

Only valid in combination with time_in_force=`\"good_til_cancelled\"`

+ String advanced = "advanced_example"; // String | Advanced option order type. If you have posted an advanced option order, it is necessary to re-supply this parameter when editing it (Only for options) + BigDecimal stopPrice = new BigDecimal(); // BigDecimal | Stop price, required for stop limit orders (Only for stop orders) + try { + Object result = apiInstance.privateEditGet(orderId, amount, price, postOnly, advanced, stopPrice); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateEditGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -890,6 +1095,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetAccountSummaryGet** > Object privateGetAccountSummaryGet(currency, extended) @@ -899,28 +1109,37 @@ Retrieves user account summary. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String currency = "currency_example"; // String | The currency symbol -Boolean extended = false; // Boolean | Include additional fields -try { - Object result = apiInstance.privateGetAccountSummaryGet(currency, extended); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetAccountSummaryGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + Boolean extended = false; // Boolean | Include additional fields + try { + Object result = apiInstance.privateGetAccountSummaryGet(currency, extended); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetAccountSummaryGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -944,6 +1163,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetAddressBookGet** > Object privateGetAddressBookGet(currency, type) @@ -953,28 +1177,37 @@ Retrieves address book of given type ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String currency = "currency_example"; // String | The currency symbol -String type = "type_example"; // String | Address book type -try { - Object result = apiInstance.privateGetAddressBookGet(currency, type); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetAddressBookGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String type = "type_example"; // String | Address book type + try { + Object result = apiInstance.privateGetAddressBookGet(currency, type); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetAddressBookGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -998,6 +1231,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetCurrentDepositAddressGet** > Object privateGetCurrentDepositAddressGet(currency) @@ -1007,27 +1245,36 @@ Retrieve deposit address for currency ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String currency = "currency_example"; // String | The currency symbol -try { - Object result = apiInstance.privateGetCurrentDepositAddressGet(currency); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetCurrentDepositAddressGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + try { + Object result = apiInstance.privateGetCurrentDepositAddressGet(currency); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetCurrentDepositAddressGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1050,6 +1297,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetDepositsGet** > Object privateGetDepositsGet(currency, count, offset) @@ -1059,29 +1311,38 @@ Retrieve the latest users deposits ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String currency = "currency_example"; // String | The currency symbol -Integer count = 56; // Integer | Number of requested items, default - `10` -Integer offset = 10; // Integer | The offset for pagination, default - `0` -try { - Object result = apiInstance.privateGetDepositsGet(currency, count, offset); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetDepositsGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + Integer count = 56; // Integer | Number of requested items, default - `10` + Integer offset = 10; // Integer | The offset for pagination, default - `0` + try { + Object result = apiInstance.privateGetDepositsGet(currency, count, offset); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetDepositsGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1106,6 +1367,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetEmailLanguageGet** > Object privateGetEmailLanguageGet() @@ -1115,26 +1381,35 @@ Retrieves the language to be used for emails. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -try { - Object result = apiInstance.privateGetEmailLanguageGet(); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetEmailLanguageGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + try { + Object result = apiInstance.privateGetEmailLanguageGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetEmailLanguageGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1154,6 +1429,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetMarginsGet** > Object privateGetMarginsGet(instrumentName, amount, price) @@ -1163,29 +1443,38 @@ Get margins for given instrument, amount and price. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -BigDecimal amount = 1; // BigDecimal | Amount, integer for future, float for option. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH. -BigDecimal price = new BigDecimal(); // BigDecimal | Price -try { - Object result = apiInstance.privateGetMarginsGet(instrumentName, amount, price); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetMarginsGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + BigDecimal amount = 1; // BigDecimal | Amount, integer for future, float for option. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH. + BigDecimal price = new BigDecimal(); // BigDecimal | Price + try { + Object result = apiInstance.privateGetMarginsGet(instrumentName, amount, price); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetMarginsGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1210,6 +1499,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetNewAnnouncementsGet** > Object privateGetNewAnnouncementsGet() @@ -1219,26 +1513,35 @@ Retrieves announcements that have not been marked read by the user. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -try { - Object result = apiInstance.privateGetNewAnnouncementsGet(); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetNewAnnouncementsGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + try { + Object result = apiInstance.privateGetNewAnnouncementsGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetNewAnnouncementsGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1258,6 +1561,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetOpenOrdersByCurrencyGet** > Object privateGetOpenOrdersByCurrencyGet(currency, kind, type) @@ -1267,29 +1575,38 @@ Retrieves list of user's open orders. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String currency = "currency_example"; // String | The currency symbol -String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered -String type = "type_example"; // String | Order type, default - `all` -try { - Object result = apiInstance.privateGetOpenOrdersByCurrencyGet(currency, kind, type); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetOpenOrdersByCurrencyGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered + String type = "type_example"; // String | Order type, default - `all` + try { + Object result = apiInstance.privateGetOpenOrdersByCurrencyGet(currency, kind, type); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetOpenOrdersByCurrencyGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1314,6 +1631,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetOpenOrdersByInstrumentGet** > Object privateGetOpenOrdersByInstrumentGet(instrumentName, type) @@ -1323,28 +1645,37 @@ Retrieves list of user's open orders within given Instrument. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -String type = "type_example"; // String | Order type, default - `all` -try { - Object result = apiInstance.privateGetOpenOrdersByInstrumentGet(instrumentName, type); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetOpenOrdersByInstrumentGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + String type = "type_example"; // String | Order type, default - `all` + try { + Object result = apiInstance.privateGetOpenOrdersByInstrumentGet(instrumentName, type); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetOpenOrdersByInstrumentGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1368,6 +1699,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetOrderHistoryByCurrencyGet** > Object privateGetOrderHistoryByCurrencyGet(currency, kind, count, offset, includeOld, includeUnfilled) @@ -1377,32 +1713,41 @@ Retrieves history of orders that have been partially or fully filled. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String currency = "currency_example"; // String | The currency symbol -String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered -Integer count = 56; // Integer | Number of requested items, default - `20` -Integer offset = 10; // Integer | The offset for pagination, default - `0` -Boolean includeOld = false; // Boolean | Include in result orders older than 2 days, default - `false` -Boolean includeUnfilled = false; // Boolean | Include in result fully unfilled closed orders, default - `false` -try { - Object result = apiInstance.privateGetOrderHistoryByCurrencyGet(currency, kind, count, offset, includeOld, includeUnfilled); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetOrderHistoryByCurrencyGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered + Integer count = 56; // Integer | Number of requested items, default - `20` + Integer offset = 10; // Integer | The offset for pagination, default - `0` + Boolean includeOld = false; // Boolean | Include in result orders older than 2 days, default - `false` + Boolean includeUnfilled = false; // Boolean | Include in result fully unfilled closed orders, default - `false` + try { + Object result = apiInstance.privateGetOrderHistoryByCurrencyGet(currency, kind, count, offset, includeOld, includeUnfilled); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetOrderHistoryByCurrencyGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1430,6 +1775,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetOrderHistoryByInstrumentGet** > Object privateGetOrderHistoryByInstrumentGet(instrumentName, count, offset, includeOld, includeUnfilled) @@ -1439,31 +1789,40 @@ Retrieves history of orders that have been partially or fully filled. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -Integer count = 56; // Integer | Number of requested items, default - `20` -Integer offset = 10; // Integer | The offset for pagination, default - `0` -Boolean includeOld = false; // Boolean | Include in result orders older than 2 days, default - `false` -Boolean includeUnfilled = false; // Boolean | Include in result fully unfilled closed orders, default - `false` -try { - Object result = apiInstance.privateGetOrderHistoryByInstrumentGet(instrumentName, count, offset, includeOld, includeUnfilled); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetOrderHistoryByInstrumentGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + Integer count = 56; // Integer | Number of requested items, default - `20` + Integer offset = 10; // Integer | The offset for pagination, default - `0` + Boolean includeOld = false; // Boolean | Include in result orders older than 2 days, default - `false` + Boolean includeUnfilled = false; // Boolean | Include in result fully unfilled closed orders, default - `false` + try { + Object result = apiInstance.privateGetOrderHistoryByInstrumentGet(instrumentName, count, offset, includeOld, includeUnfilled); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetOrderHistoryByInstrumentGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1490,6 +1849,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetOrderMarginByIdsGet** > Object privateGetOrderMarginByIdsGet(ids) @@ -1499,27 +1863,36 @@ Retrieves initial margins of given orders ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -List ids = Arrays.asList(); // List | Ids of orders -try { - Object result = apiInstance.privateGetOrderMarginByIdsGet(ids); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetOrderMarginByIdsGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + List ids = Arrays.asList(); // List | Ids of orders + try { + Object result = apiInstance.privateGetOrderMarginByIdsGet(ids); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetOrderMarginByIdsGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1542,6 +1915,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetOrderStateGet** > Object privateGetOrderStateGet(orderId) @@ -1551,27 +1929,36 @@ Retrieve the current state of an order. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String orderId = ETH-100234; // String | The order id -try { - Object result = apiInstance.privateGetOrderStateGet(orderId); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetOrderStateGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String orderId = ETH-100234; // String | The order id + try { + Object result = apiInstance.privateGetOrderStateGet(orderId); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetOrderStateGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1594,6 +1981,12 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | +**400** | result when used via rest/HTTP | - | + # **privateGetPositionGet** > Object privateGetPositionGet(instrumentName) @@ -1603,27 +1996,36 @@ Retrieve user position. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -try { - Object result = apiInstance.privateGetPositionGet(instrumentName); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetPositionGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + try { + Object result = apiInstance.privateGetPositionGet(instrumentName); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetPositionGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1646,6 +2048,12 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | When successful returns position | - | +**400** | When some error occurs | - | + # **privateGetPositionsGet** > Object privateGetPositionsGet(currency, kind) @@ -1655,28 +2063,37 @@ Retrieve user positions. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String currency = "currency_example"; // String | -String kind = "kind_example"; // String | Kind filter on positions -try { - Object result = apiInstance.privateGetPositionsGet(currency, kind); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetPositionsGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String currency = "currency_example"; // String | + String kind = "kind_example"; // String | Kind filter on positions + try { + Object result = apiInstance.privateGetPositionsGet(currency, kind); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetPositionsGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1700,6 +2117,12 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | When successful returns array of positions | - | +**400** | When some error occurs | - | + # **privateGetSettlementHistoryByCurrencyGet** > Object privateGetSettlementHistoryByCurrencyGet(currency, type, count) @@ -1709,29 +2132,38 @@ Retrieves settlement, delivery and bankruptcy events that have affected your acc ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String currency = "currency_example"; // String | The currency symbol -String type = "type_example"; // String | Settlement type -Integer count = 56; // Integer | Number of requested items, default - `20` -try { - Object result = apiInstance.privateGetSettlementHistoryByCurrencyGet(currency, type, count); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetSettlementHistoryByCurrencyGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String type = "type_example"; // String | Settlement type + Integer count = 56; // Integer | Number of requested items, default - `20` + try { + Object result = apiInstance.privateGetSettlementHistoryByCurrencyGet(currency, type, count); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetSettlementHistoryByCurrencyGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1756,6 +2188,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetSettlementHistoryByInstrumentGet** > Object privateGetSettlementHistoryByInstrumentGet(instrumentName, type, count) @@ -1765,29 +2202,38 @@ Retrieves public settlement, delivery and bankruptcy events filtered by instrume ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -String type = "type_example"; // String | Settlement type -Integer count = 56; // Integer | Number of requested items, default - `20` -try { - Object result = apiInstance.privateGetSettlementHistoryByInstrumentGet(instrumentName, type, count); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetSettlementHistoryByInstrumentGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + String type = "type_example"; // String | Settlement type + Integer count = 56; // Integer | Number of requested items, default - `20` + try { + Object result = apiInstance.privateGetSettlementHistoryByInstrumentGet(instrumentName, type, count); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetSettlementHistoryByInstrumentGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1812,6 +2258,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetSubaccountsGet** > Object privateGetSubaccountsGet(withPortfolio) @@ -1821,27 +2272,36 @@ Get information about subaccounts ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -Boolean withPortfolio = true; // Boolean | -try { - Object result = apiInstance.privateGetSubaccountsGet(withPortfolio); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetSubaccountsGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + Boolean withPortfolio = true; // Boolean | + try { + Object result = apiInstance.privateGetSubaccountsGet(withPortfolio); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetSubaccountsGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1864,6 +2324,12 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | +**401** | not authorised | - | + # **privateGetTransfersGet** > Object privateGetTransfersGet(currency, count, offset) @@ -1873,29 +2339,38 @@ Adds new entry to address book of given type ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String currency = "currency_example"; // String | The currency symbol -Integer count = 56; // Integer | Number of requested items, default - `10` -Integer offset = 10; // Integer | The offset for pagination, default - `0` -try { - Object result = apiInstance.privateGetTransfersGet(currency, count, offset); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetTransfersGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + Integer count = 56; // Integer | Number of requested items, default - `10` + Integer offset = 10; // Integer | The offset for pagination, default - `0` + try { + Object result = apiInstance.privateGetTransfersGet(currency, count, offset); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetTransfersGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1920,6 +2395,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetUserTradesByCurrencyAndTimeGet** > Object privateGetUserTradesByCurrencyAndTimeGet(currency, startTimestamp, endTimestamp, kind, count, includeOld, sorting) @@ -1929,33 +2409,42 @@ Retrieve the latest user trades that have occurred for instruments in a specific ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String currency = "currency_example"; // String | The currency symbol -Integer startTimestamp = 1536569522277; // Integer | The earliest timestamp to return result for -Integer endTimestamp = 1536569522277; // Integer | The most recent timestamp to return result for -String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered -Integer count = 56; // Integer | Number of requested items, default - `10` -Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` -String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) -try { - Object result = apiInstance.privateGetUserTradesByCurrencyAndTimeGet(currency, startTimestamp, endTimestamp, kind, count, includeOld, sorting); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetUserTradesByCurrencyAndTimeGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + Integer startTimestamp = 1536569522277; // Integer | The earliest timestamp to return result for + Integer endTimestamp = 1536569522277; // Integer | The most recent timestamp to return result for + String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered + Integer count = 56; // Integer | Number of requested items, default - `10` + Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` + String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + try { + Object result = apiInstance.privateGetUserTradesByCurrencyAndTimeGet(currency, startTimestamp, endTimestamp, kind, count, includeOld, sorting); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetUserTradesByCurrencyAndTimeGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1984,6 +2473,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetUserTradesByCurrencyGet** > Object privateGetUserTradesByCurrencyGet(currency, kind, startId, endId, count, includeOld, sorting) @@ -1993,33 +2487,42 @@ Retrieve the latest user trades that have occurred for instruments in a specific ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String currency = "currency_example"; // String | The currency symbol -String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered -String startId = "startId_example"; // String | The ID number of the first trade to be returned -String endId = "endId_example"; // String | The ID number of the last trade to be returned -Integer count = 56; // Integer | Number of requested items, default - `10` -Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` -String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) -try { - Object result = apiInstance.privateGetUserTradesByCurrencyGet(currency, kind, startId, endId, count, includeOld, sorting); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetUserTradesByCurrencyGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered + String startId = "startId_example"; // String | The ID number of the first trade to be returned + String endId = "endId_example"; // String | The ID number of the last trade to be returned + Integer count = 56; // Integer | Number of requested items, default - `10` + Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` + String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + try { + Object result = apiInstance.privateGetUserTradesByCurrencyGet(currency, kind, startId, endId, count, includeOld, sorting); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetUserTradesByCurrencyGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -2048,6 +2551,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetUserTradesByInstrumentAndTimeGet** > Object privateGetUserTradesByInstrumentAndTimeGet(instrumentName, startTimestamp, endTimestamp, count, includeOld, sorting) @@ -2057,32 +2565,41 @@ Retrieve the latest user trades that have occurred for a specific instrument and ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -Integer startTimestamp = 1536569522277; // Integer | The earliest timestamp to return result for -Integer endTimestamp = 1536569522277; // Integer | The most recent timestamp to return result for -Integer count = 56; // Integer | Number of requested items, default - `10` -Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` -String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) -try { - Object result = apiInstance.privateGetUserTradesByInstrumentAndTimeGet(instrumentName, startTimestamp, endTimestamp, count, includeOld, sorting); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetUserTradesByInstrumentAndTimeGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + Integer startTimestamp = 1536569522277; // Integer | The earliest timestamp to return result for + Integer endTimestamp = 1536569522277; // Integer | The most recent timestamp to return result for + Integer count = 56; // Integer | Number of requested items, default - `10` + Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` + String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + try { + Object result = apiInstance.privateGetUserTradesByInstrumentAndTimeGet(instrumentName, startTimestamp, endTimestamp, count, includeOld, sorting); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetUserTradesByInstrumentAndTimeGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -2110,6 +2627,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetUserTradesByInstrumentGet** > Object privateGetUserTradesByInstrumentGet(instrumentName, startSeq, endSeq, count, includeOld, sorting) @@ -2119,32 +2641,41 @@ Retrieve the latest user trades that have occurred for a specific instrument. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -Integer startSeq = 56; // Integer | The sequence number of the first trade to be returned -Integer endSeq = 56; // Integer | The sequence number of the last trade to be returned -Integer count = 56; // Integer | Number of requested items, default - `10` -Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` -String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) -try { - Object result = apiInstance.privateGetUserTradesByInstrumentGet(instrumentName, startSeq, endSeq, count, includeOld, sorting); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetUserTradesByInstrumentGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + Integer startSeq = 56; // Integer | The sequence number of the first trade to be returned + Integer endSeq = 56; // Integer | The sequence number of the last trade to be returned + Integer count = 56; // Integer | Number of requested items, default - `10` + Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` + String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + try { + Object result = apiInstance.privateGetUserTradesByInstrumentGet(instrumentName, startSeq, endSeq, count, includeOld, sorting); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetUserTradesByInstrumentGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -2172,6 +2703,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetUserTradesByOrderGet** > Object privateGetUserTradesByOrderGet(orderId, sorting) @@ -2181,28 +2717,37 @@ Retrieve the list of user trades that was created for given order ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String orderId = ETH-100234; // String | The order id -String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) -try { - Object result = apiInstance.privateGetUserTradesByOrderGet(orderId, sorting); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetUserTradesByOrderGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String orderId = ETH-100234; // String | The order id + String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + try { + Object result = apiInstance.privateGetUserTradesByOrderGet(orderId, sorting); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetUserTradesByOrderGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -2226,6 +2771,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetWithdrawalsGet** > Object privateGetWithdrawalsGet(currency, count, offset) @@ -2235,29 +2785,38 @@ Retrieve the latest users withdrawals ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String currency = "currency_example"; // String | The currency symbol -Integer count = 56; // Integer | Number of requested items, default - `10` -Integer offset = 10; // Integer | The offset for pagination, default - `0` -try { - Object result = apiInstance.privateGetWithdrawalsGet(currency, count, offset); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateGetWithdrawalsGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + Integer count = 56; // Integer | Number of requested items, default - `10` + Integer offset = 10; // Integer | The offset for pagination, default - `0` + try { + Object result = apiInstance.privateGetWithdrawalsGet(currency, count, offset); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateGetWithdrawalsGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -2282,6 +2841,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateRemoveFromAddressBookGet** > Object privateRemoveFromAddressBookGet(currency, type, address, tfa) @@ -2291,30 +2855,39 @@ Adds new entry to address book of given type ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String currency = "currency_example"; // String | The currency symbol -String type = "type_example"; // String | Address book type -String address = "address_example"; // String | Address in currency format, it must be in address book -String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account -try { - Object result = apiInstance.privateRemoveFromAddressBookGet(currency, type, address, tfa); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateRemoveFromAddressBookGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String type = "type_example"; // String | Address book type + String address = "address_example"; // String | Address in currency format, it must be in address book + String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account + try { + Object result = apiInstance.privateRemoveFromAddressBookGet(currency, type, address, tfa); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateRemoveFromAddressBookGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -2340,6 +2913,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateSellGet** > Object privateSellGet(instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced) @@ -2349,38 +2927,47 @@ Places a sell order for an instrument. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -BigDecimal amount = new BigDecimal(); // BigDecimal | It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH -String type = "type_example"; // String | The order type, default: `\"limit\"` -String label = "label_example"; // String | user defined label for the order (maximum 32 characters) -BigDecimal price = new BigDecimal(); // BigDecimal |

The order price in base currency (Only for limit and stop_limit orders)

When adding order with advanced=usd, the field price should be the option price value in USD.

When adding order with advanced=implv, the field price should be a value of implied volatility in percentages. For example, price=100, means implied volatility of 100%

-String timeInForce = "good_til_cancelled"; // String |

Specifies how long the order remains in effect. Default `\"good_til_cancelled\"`

  • `\"good_til_cancelled\"` - unfilled order remains in order book until cancelled
  • `\"fill_or_kill\"` - execute a transaction immediately and completely or not at all
  • `\"immediate_or_cancel\"` - execute a transaction immediately, and any portion of the order that cannot be immediately filled is cancelled
-BigDecimal maxShow = new BigDecimal(); // BigDecimal | Maximum amount within an order to be shown to other customers, `0` for invisible order -Boolean postOnly = true; // Boolean |

If true, the order is considered post-only. If the new price would cause the order to be filled immediately (as taker), the price will be changed to be just below the bid.

Only valid in combination with time_in_force=`\"good_til_cancelled\"`

-Boolean reduceOnly = false; // Boolean | If `true`, the order is considered reduce-only which is intended to only reduce a current position -BigDecimal stopPrice = new BigDecimal(); // BigDecimal | Stop price, required for stop limit orders (Only for stop orders) -String trigger = "trigger_example"; // String | Defines trigger type, required for `\"stop_limit\"` order type -String advanced = "advanced_example"; // String | Advanced option order type. (Only for options) -try { - Object result = apiInstance.privateSellGet(instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateSellGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + BigDecimal amount = new BigDecimal(); // BigDecimal | It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH + String type = "type_example"; // String | The order type, default: `\"limit\"` + String label = "label_example"; // String | user defined label for the order (maximum 32 characters) + BigDecimal price = new BigDecimal(); // BigDecimal |

The order price in base currency (Only for limit and stop_limit orders)

When adding order with advanced=usd, the field price should be the option price value in USD.

When adding order with advanced=implv, the field price should be a value of implied volatility in percentages. For example, price=100, means implied volatility of 100%

+ String timeInForce = "good_til_cancelled"; // String |

Specifies how long the order remains in effect. Default `\"good_til_cancelled\"`

  • `\"good_til_cancelled\"` - unfilled order remains in order book until cancelled
  • `\"fill_or_kill\"` - execute a transaction immediately and completely or not at all
  • `\"immediate_or_cancel\"` - execute a transaction immediately, and any portion of the order that cannot be immediately filled is cancelled
+ BigDecimal maxShow = new BigDecimal(); // BigDecimal | Maximum amount within an order to be shown to other customers, `0` for invisible order + Boolean postOnly = true; // Boolean |

If true, the order is considered post-only. If the new price would cause the order to be filled immediately (as taker), the price will be changed to be just below the bid.

Only valid in combination with time_in_force=`\"good_til_cancelled\"`

+ Boolean reduceOnly = false; // Boolean | If `true`, the order is considered reduce-only which is intended to only reduce a current position + BigDecimal stopPrice = new BigDecimal(); // BigDecimal | Stop price, required for stop limit orders (Only for stop orders) + String trigger = "trigger_example"; // String | Defines trigger type, required for `\"stop_limit\"` order type + String advanced = "advanced_example"; // String | Advanced option order type. (Only for options) + try { + Object result = apiInstance.privateSellGet(instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateSellGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -2414,6 +3001,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateSetAnnouncementAsReadGet** > Object privateSetAnnouncementAsReadGet(announcementId) @@ -2423,27 +3015,36 @@ Marks an announcement as read, so it will not be shown in `get_new_announce ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -BigDecimal announcementId = new BigDecimal(); // BigDecimal | the ID of the announcement -try { - Object result = apiInstance.privateSetAnnouncementAsReadGet(announcementId); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateSetAnnouncementAsReadGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + BigDecimal announcementId = new BigDecimal(); // BigDecimal | the ID of the announcement + try { + Object result = apiInstance.privateSetAnnouncementAsReadGet(announcementId); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateSetAnnouncementAsReadGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -2466,6 +3067,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateSetEmailForSubaccountGet** > Object privateSetEmailForSubaccountGet(sid, email) @@ -2475,28 +3081,37 @@ Assign an email address to a subaccount. User will receive an email with confirm ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -Integer sid = 56; // Integer | The user id for the subaccount -String email = subaccount_1@email.com; // String | The email address for the subaccount -try { - Object result = apiInstance.privateSetEmailForSubaccountGet(sid, email); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateSetEmailForSubaccountGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + Integer sid = 56; // Integer | The user id for the subaccount + String email = subaccount_1@email.com; // String | The email address for the subaccount + try { + Object result = apiInstance.privateSetEmailForSubaccountGet(sid, email); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateSetEmailForSubaccountGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -2520,6 +3135,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateSetEmailLanguageGet** > Object privateSetEmailLanguageGet(language) @@ -2529,27 +3149,36 @@ Changes the language to be used for emails. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String language = en; // String | The abbreviated language name. Valid values include `\"en\"`, `\"ko\"`, `\"zh\"` -try { - Object result = apiInstance.privateSetEmailLanguageGet(language); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateSetEmailLanguageGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String language = en; // String | The abbreviated language name. Valid values include `\"en\"`, `\"ko\"`, `\"zh\"` + try { + Object result = apiInstance.privateSetEmailLanguageGet(language); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateSetEmailLanguageGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -2572,6 +3201,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateSetPasswordForSubaccountGet** > Object privateSetPasswordForSubaccountGet(sid, password) @@ -2581,28 +3215,37 @@ Set the password for the subaccount ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -Integer sid = 56; // Integer | The user id for the subaccount -String password = "password_example"; // String | The password for the subaccount -try { - Object result = apiInstance.privateSetPasswordForSubaccountGet(sid, password); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateSetPasswordForSubaccountGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + Integer sid = 56; // Integer | The user id for the subaccount + String password = "password_example"; // String | The password for the subaccount + try { + Object result = apiInstance.privateSetPasswordForSubaccountGet(sid, password); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateSetPasswordForSubaccountGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -2626,6 +3269,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateSubmitTransferToSubaccountGet** > Object privateSubmitTransferToSubaccountGet(currency, amount, destination) @@ -2635,29 +3283,38 @@ Transfer funds to a subaccount. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String currency = "currency_example"; // String | The currency symbol -BigDecimal amount = new BigDecimal(); // BigDecimal | Amount of funds to be transferred -Integer destination = 1; // Integer | Id of destination subaccount -try { - Object result = apiInstance.privateSubmitTransferToSubaccountGet(currency, amount, destination); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateSubmitTransferToSubaccountGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + BigDecimal amount = new BigDecimal(); // BigDecimal | Amount of funds to be transferred + Integer destination = 1; // Integer | Id of destination subaccount + try { + Object result = apiInstance.privateSubmitTransferToSubaccountGet(currency, amount, destination); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateSubmitTransferToSubaccountGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -2682,6 +3339,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateSubmitTransferToUserGet** > Object privateSubmitTransferToUserGet(currency, amount, destination, tfa) @@ -2691,30 +3353,39 @@ Transfer funds to a another user. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String currency = "currency_example"; // String | The currency symbol -BigDecimal amount = new BigDecimal(); // BigDecimal | Amount of funds to be transferred -String destination = "destination_example"; // String | Destination address from address book -String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account -try { - Object result = apiInstance.privateSubmitTransferToUserGet(currency, amount, destination, tfa); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateSubmitTransferToUserGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + BigDecimal amount = new BigDecimal(); // BigDecimal | Amount of funds to be transferred + String destination = "destination_example"; // String | Destination address from address book + String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account + try { + Object result = apiInstance.privateSubmitTransferToUserGet(currency, amount, destination, tfa); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateSubmitTransferToUserGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -2740,6 +3411,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateToggleDepositAddressCreationGet** > Object privateToggleDepositAddressCreationGet(currency, state) @@ -2749,28 +3425,37 @@ Enable or disable deposit address creation ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String currency = "currency_example"; // String | The currency symbol -Boolean state = true; // Boolean | -try { - Object result = apiInstance.privateToggleDepositAddressCreationGet(currency, state); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateToggleDepositAddressCreationGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + Boolean state = true; // Boolean | + try { + Object result = apiInstance.privateToggleDepositAddressCreationGet(currency, state); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateToggleDepositAddressCreationGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -2794,6 +3479,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateToggleNotificationsFromSubaccountGet** > Object privateToggleNotificationsFromSubaccountGet(sid, state) @@ -2803,28 +3493,37 @@ Enable or disable sending of notifications for the subaccount. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -Integer sid = 56; // Integer | The user id for the subaccount -Boolean state = true; // Boolean | enable (`true`) or disable (`false`) notifications -try { - Object result = apiInstance.privateToggleNotificationsFromSubaccountGet(sid, state); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateToggleNotificationsFromSubaccountGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + Integer sid = 56; // Integer | The user id for the subaccount + Boolean state = true; // Boolean | enable (`true`) or disable (`false`) notifications + try { + Object result = apiInstance.privateToggleNotificationsFromSubaccountGet(sid, state); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateToggleNotificationsFromSubaccountGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -2848,6 +3547,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateToggleSubaccountLoginGet** > Object privateToggleSubaccountLoginGet(sid, state) @@ -2857,28 +3561,37 @@ Enable or disable login for a subaccount. If login is disabled and a session for ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -Integer sid = 56; // Integer | The user id for the subaccount -String state = "state_example"; // String | enable or disable login. -try { - Object result = apiInstance.privateToggleSubaccountLoginGet(sid, state); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateToggleSubaccountLoginGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + Integer sid = 56; // Integer | The user id for the subaccount + String state = "state_example"; // String | enable or disable login. + try { + Object result = apiInstance.privateToggleSubaccountLoginGet(sid, state); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateToggleSubaccountLoginGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -2902,6 +3615,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateWithdrawGet** > Object privateWithdrawGet(currency, address, amount, priority, tfa) @@ -2911,31 +3629,40 @@ Creates a new withdrawal request ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PrivateApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PrivateApi apiInstance = new PrivateApi(); -String currency = "currency_example"; // String | The currency symbol -String address = "address_example"; // String | Address in currency format, it must be in address book -BigDecimal amount = new BigDecimal(); // BigDecimal | Amount of funds to be withdrawn -String priority = "priority_example"; // String | Withdrawal priority, optional for BTC, default: `high` -String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account -try { - Object result = apiInstance.privateWithdrawGet(currency, address, amount, priority, tfa); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PrivateApi#privateWithdrawGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PrivateApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PrivateApi apiInstance = new PrivateApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String address = "address_example"; // String | Address in currency format, it must be in address book + BigDecimal amount = new BigDecimal(); // BigDecimal | Amount of funds to be withdrawn + String priority = "priority_example"; // String | Withdrawal priority, optional for BTC, default: `high` + String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account + try { + Object result = apiInstance.privateWithdrawGet(currency, address, amount, priority, tfa); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PrivateApi#privateWithdrawGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -2962,3 +3689,8 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + diff --git a/java/docs/PublicApi.md b/java/docs/PublicApi.md index ddda9c8..6b39549 100644 --- a/java/docs/PublicApi.md +++ b/java/docs/PublicApi.md @@ -40,37 +40,46 @@ Retrieve an Oauth access token, to be used for authentication of 'private ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PublicApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PublicApi apiInstance = new PublicApi(); -String grantType = "grantType_example"; // String | Method of authentication -String username = your_email@mail.com; // String | Required for grant type `password` -String password = your_password; // String | Required for grant type `password` -String clientId = "clientId_example"; // String | Required for grant type `client_credentials` and `client_signature` -String clientSecret = "clientSecret_example"; // String | Required for grant type `client_credentials` -String refreshToken = "refreshToken_example"; // String | Required for grant type `refresh_token` -String timestamp = "timestamp_example"; // String | Required for grant type `client_signature`, provides time when request has been generated -String signature = "signature_example"; // String | Required for grant type `client_signature`; it's a cryptographic signature calculated over provided fields using user **secret key**. The signature should be calculated as an HMAC (Hash-based Message Authentication Code) with `SHA256` hash algorithm -String nonce = "nonce_example"; // String | Optional for grant type `client_signature`; delivers user generated initialization vector for the server token -String state = "state_example"; // String | Will be passed back in the response -String scope = connection; // String | Describes type of the access for assigned token, possible values: `connection`, `session`, `session:name`, `trade:[read, read_write, none]`, `wallet:[read, read_write, none]`, `account:[read, read_write, none]`, `expires:NUMBER` (token will expire after `NUMBER` of seconds).

**NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read``` -try { - Object result = apiInstance.publicAuthGet(grantType, username, password, clientId, clientSecret, refreshToken, timestamp, signature, nonce, state, scope); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PublicApi#publicAuthGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PublicApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PublicApi apiInstance = new PublicApi(defaultClient); + String grantType = "grantType_example"; // String | Method of authentication + String username = your_email@mail.com; // String | Required for grant type `password` + String password = your_password; // String | Required for grant type `password` + String clientId = "clientId_example"; // String | Required for grant type `client_credentials` and `client_signature` + String clientSecret = "clientSecret_example"; // String | Required for grant type `client_credentials` + String refreshToken = "refreshToken_example"; // String | Required for grant type `refresh_token` + String timestamp = "timestamp_example"; // String | Required for grant type `client_signature`, provides time when request has been generated + String signature = "signature_example"; // String | Required for grant type `client_signature`; it's a cryptographic signature calculated over provided fields using user **secret key**. The signature should be calculated as an HMAC (Hash-based Message Authentication Code) with `SHA256` hash algorithm + String nonce = "nonce_example"; // String | Optional for grant type `client_signature`; delivers user generated initialization vector for the server token + String state = "state_example"; // String | Will be passed back in the response + String scope = connection; // String | Describes type of the access for assigned token, possible values: `connection`, `session`, `session:name`, `trade:[read, read_write, none]`, `wallet:[read, read_write, none]`, `account:[read, read_write, none]`, `expires:NUMBER` (token will expire after `NUMBER` of seconds).

**NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read``` + try { + Object result = apiInstance.publicAuthGet(grantType, username, password, clientId, clientSecret, refreshToken, timestamp, signature, nonce, state, scope); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PublicApi#publicAuthGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -103,6 +112,12 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | +**429** | over limit | - | + # **publicGetAnnouncementsGet** > Object publicGetAnnouncementsGet() @@ -112,26 +127,35 @@ Retrieves announcements from the last 30 days. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PublicApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PublicApi apiInstance = new PublicApi(); -try { - Object result = apiInstance.publicGetAnnouncementsGet(); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PublicApi#publicGetAnnouncementsGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PublicApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PublicApi apiInstance = new PublicApi(defaultClient); + try { + Object result = apiInstance.publicGetAnnouncementsGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PublicApi#publicGetAnnouncementsGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -151,6 +175,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetBookSummaryByCurrencyGet** > Object publicGetBookSummaryByCurrencyGet(currency, kind) @@ -160,28 +189,37 @@ Retrieves the summary information such as open interest, 24h volume, etc. for al ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PublicApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PublicApi apiInstance = new PublicApi(); -String currency = "currency_example"; // String | The currency symbol -String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered -try { - Object result = apiInstance.publicGetBookSummaryByCurrencyGet(currency, kind); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PublicApi#publicGetBookSummaryByCurrencyGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PublicApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PublicApi apiInstance = new PublicApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered + try { + Object result = apiInstance.publicGetBookSummaryByCurrencyGet(currency, kind); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PublicApi#publicGetBookSummaryByCurrencyGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -205,6 +243,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetBookSummaryByInstrumentGet** > Object publicGetBookSummaryByInstrumentGet(instrumentName) @@ -214,27 +257,36 @@ Retrieves the summary information such as open interest, 24h volume, etc. for a ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PublicApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PublicApi apiInstance = new PublicApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -try { - Object result = apiInstance.publicGetBookSummaryByInstrumentGet(instrumentName); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PublicApi#publicGetBookSummaryByInstrumentGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PublicApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PublicApi apiInstance = new PublicApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + try { + Object result = apiInstance.publicGetBookSummaryByInstrumentGet(instrumentName); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PublicApi#publicGetBookSummaryByInstrumentGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -257,6 +309,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetContractSizeGet** > Object publicGetContractSizeGet(instrumentName) @@ -266,27 +323,36 @@ Retrieves contract size of provided instrument. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PublicApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PublicApi apiInstance = new PublicApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -try { - Object result = apiInstance.publicGetContractSizeGet(instrumentName); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PublicApi#publicGetContractSizeGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PublicApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PublicApi apiInstance = new PublicApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + try { + Object result = apiInstance.publicGetContractSizeGet(instrumentName); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PublicApi#publicGetContractSizeGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -309,6 +375,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **publicGetCurrenciesGet** > Object publicGetCurrenciesGet() @@ -318,26 +389,35 @@ Retrieves all cryptocurrencies supported by the API. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PublicApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PublicApi apiInstance = new PublicApi(); -try { - Object result = apiInstance.publicGetCurrenciesGet(); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PublicApi#publicGetCurrenciesGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PublicApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PublicApi apiInstance = new PublicApi(defaultClient); + try { + Object result = apiInstance.publicGetCurrenciesGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PublicApi#publicGetCurrenciesGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -357,6 +437,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **publicGetFundingChartDataGet** > Object publicGetFundingChartDataGet(instrumentName, length) @@ -366,28 +451,37 @@ Retrieve the latest user trades that have occurred for PERPETUAL instruments in ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PublicApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PublicApi apiInstance = new PublicApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -String length = "length_example"; // String | Specifies time period. `8h` - 8 hours, `24h` - 24 hours -try { - Object result = apiInstance.publicGetFundingChartDataGet(instrumentName, length); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PublicApi#publicGetFundingChartDataGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PublicApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PublicApi apiInstance = new PublicApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + String length = "length_example"; // String | Specifies time period. `8h` - 8 hours, `24h` - 24 hours + try { + Object result = apiInstance.publicGetFundingChartDataGet(instrumentName, length); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PublicApi#publicGetFundingChartDataGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -411,6 +505,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetHistoricalVolatilityGet** > Object publicGetHistoricalVolatilityGet(currency) @@ -420,27 +519,36 @@ Provides information about historical volatility for given cryptocurrency. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PublicApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PublicApi apiInstance = new PublicApi(); -String currency = "currency_example"; // String | The currency symbol -try { - Object result = apiInstance.publicGetHistoricalVolatilityGet(currency); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PublicApi#publicGetHistoricalVolatilityGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PublicApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PublicApi apiInstance = new PublicApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + try { + Object result = apiInstance.publicGetHistoricalVolatilityGet(currency); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PublicApi#publicGetHistoricalVolatilityGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -463,6 +571,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **publicGetIndexGet** > Object publicGetIndexGet(currency) @@ -472,27 +585,36 @@ Retrieves the current index price for the instruments, for the selected currency ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PublicApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PublicApi apiInstance = new PublicApi(); -String currency = "currency_example"; // String | The currency symbol -try { - Object result = apiInstance.publicGetIndexGet(currency); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PublicApi#publicGetIndexGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PublicApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PublicApi apiInstance = new PublicApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + try { + Object result = apiInstance.publicGetIndexGet(currency); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PublicApi#publicGetIndexGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -515,6 +637,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetInstrumentsGet** > Object publicGetInstrumentsGet(currency, kind, expired) @@ -524,29 +651,38 @@ Retrieves available trading instruments. This method can be used to see which in ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PublicApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PublicApi apiInstance = new PublicApi(); -String currency = "currency_example"; // String | The currency symbol -String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered -Boolean expired = false; // Boolean | Set to true to show expired instruments instead of active ones. -try { - Object result = apiInstance.publicGetInstrumentsGet(currency, kind, expired); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PublicApi#publicGetInstrumentsGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PublicApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PublicApi apiInstance = new PublicApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered + Boolean expired = false; // Boolean | Set to true to show expired instruments instead of active ones. + try { + Object result = apiInstance.publicGetInstrumentsGet(currency, kind, expired); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PublicApi#publicGetInstrumentsGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -571,6 +707,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **publicGetLastSettlementsByCurrencyGet** > Object publicGetLastSettlementsByCurrencyGet(currency, type, count, continuation, searchStartTimestamp) @@ -580,31 +721,40 @@ Retrieves historical settlement, delivery and bankruptcy events coming from all ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PublicApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PublicApi apiInstance = new PublicApi(); -String currency = "currency_example"; // String | The currency symbol -String type = "type_example"; // String | Settlement type -Integer count = 56; // Integer | Number of requested items, default - `20` -String continuation = xY7T6cutS3t2B9YtaDkE6TS379oKnkzTvmEDUnEUP2Msa9xKWNNaT; // String | Continuation token for pagination -Integer searchStartTimestamp = 1536569522277; // Integer | The latest timestamp to return result for -try { - Object result = apiInstance.publicGetLastSettlementsByCurrencyGet(currency, type, count, continuation, searchStartTimestamp); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PublicApi#publicGetLastSettlementsByCurrencyGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PublicApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PublicApi apiInstance = new PublicApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String type = "type_example"; // String | Settlement type + Integer count = 56; // Integer | Number of requested items, default - `20` + String continuation = xY7T6cutS3t2B9YtaDkE6TS379oKnkzTvmEDUnEUP2Msa9xKWNNaT; // String | Continuation token for pagination + Integer searchStartTimestamp = 1536569522277; // Integer | The latest timestamp to return result for + try { + Object result = apiInstance.publicGetLastSettlementsByCurrencyGet(currency, type, count, continuation, searchStartTimestamp); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PublicApi#publicGetLastSettlementsByCurrencyGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -631,6 +781,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetLastSettlementsByInstrumentGet** > Object publicGetLastSettlementsByInstrumentGet(instrumentName, type, count, continuation, searchStartTimestamp) @@ -640,31 +795,40 @@ Retrieves historical public settlement, delivery and bankruptcy events filtered ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PublicApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PublicApi apiInstance = new PublicApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -String type = "type_example"; // String | Settlement type -Integer count = 56; // Integer | Number of requested items, default - `20` -String continuation = xY7T6cutS3t2B9YtaDkE6TS379oKnkzTvmEDUnEUP2Msa9xKWNNaT; // String | Continuation token for pagination -Integer searchStartTimestamp = 1536569522277; // Integer | The latest timestamp to return result for -try { - Object result = apiInstance.publicGetLastSettlementsByInstrumentGet(instrumentName, type, count, continuation, searchStartTimestamp); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PublicApi#publicGetLastSettlementsByInstrumentGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PublicApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PublicApi apiInstance = new PublicApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + String type = "type_example"; // String | Settlement type + Integer count = 56; // Integer | Number of requested items, default - `20` + String continuation = xY7T6cutS3t2B9YtaDkE6TS379oKnkzTvmEDUnEUP2Msa9xKWNNaT; // String | Continuation token for pagination + Integer searchStartTimestamp = 1536569522277; // Integer | The latest timestamp to return result for + try { + Object result = apiInstance.publicGetLastSettlementsByInstrumentGet(instrumentName, type, count, continuation, searchStartTimestamp); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PublicApi#publicGetLastSettlementsByInstrumentGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -691,6 +855,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetLastTradesByCurrencyAndTimeGet** > Object publicGetLastTradesByCurrencyAndTimeGet(currency, startTimestamp, endTimestamp, kind, count, includeOld, sorting) @@ -700,33 +869,42 @@ Retrieve the latest trades that have occurred for instruments in a specific curr ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PublicApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PublicApi apiInstance = new PublicApi(); -String currency = "currency_example"; // String | The currency symbol -Integer startTimestamp = 1536569522277; // Integer | The earliest timestamp to return result for -Integer endTimestamp = 1536569522277; // Integer | The most recent timestamp to return result for -String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered -Integer count = 56; // Integer | Number of requested items, default - `10` -Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` -String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) -try { - Object result = apiInstance.publicGetLastTradesByCurrencyAndTimeGet(currency, startTimestamp, endTimestamp, kind, count, includeOld, sorting); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PublicApi#publicGetLastTradesByCurrencyAndTimeGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PublicApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PublicApi apiInstance = new PublicApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + Integer startTimestamp = 1536569522277; // Integer | The earliest timestamp to return result for + Integer endTimestamp = 1536569522277; // Integer | The most recent timestamp to return result for + String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered + Integer count = 56; // Integer | Number of requested items, default - `10` + Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` + String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + try { + Object result = apiInstance.publicGetLastTradesByCurrencyAndTimeGet(currency, startTimestamp, endTimestamp, kind, count, includeOld, sorting); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PublicApi#publicGetLastTradesByCurrencyAndTimeGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -755,6 +933,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetLastTradesByCurrencyGet** > Object publicGetLastTradesByCurrencyGet(currency, kind, startId, endId, count, includeOld, sorting) @@ -764,33 +947,42 @@ Retrieve the latest trades that have occurred for instruments in a specific curr ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PublicApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PublicApi apiInstance = new PublicApi(); -String currency = "currency_example"; // String | The currency symbol -String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered -String startId = "startId_example"; // String | The ID number of the first trade to be returned -String endId = "endId_example"; // String | The ID number of the last trade to be returned -Integer count = 56; // Integer | Number of requested items, default - `10` -Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` -String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) -try { - Object result = apiInstance.publicGetLastTradesByCurrencyGet(currency, kind, startId, endId, count, includeOld, sorting); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PublicApi#publicGetLastTradesByCurrencyGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PublicApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PublicApi apiInstance = new PublicApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered + String startId = "startId_example"; // String | The ID number of the first trade to be returned + String endId = "endId_example"; // String | The ID number of the last trade to be returned + Integer count = 56; // Integer | Number of requested items, default - `10` + Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` + String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + try { + Object result = apiInstance.publicGetLastTradesByCurrencyGet(currency, kind, startId, endId, count, includeOld, sorting); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PublicApi#publicGetLastTradesByCurrencyGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -819,6 +1011,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetLastTradesByInstrumentAndTimeGet** > Object publicGetLastTradesByInstrumentAndTimeGet(instrumentName, startTimestamp, endTimestamp, count, includeOld, sorting) @@ -828,32 +1025,41 @@ Retrieve the latest trades that have occurred for a specific instrument and with ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PublicApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PublicApi apiInstance = new PublicApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -Integer startTimestamp = 1536569522277; // Integer | The earliest timestamp to return result for -Integer endTimestamp = 1536569522277; // Integer | The most recent timestamp to return result for -Integer count = 56; // Integer | Number of requested items, default - `10` -Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` -String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) -try { - Object result = apiInstance.publicGetLastTradesByInstrumentAndTimeGet(instrumentName, startTimestamp, endTimestamp, count, includeOld, sorting); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PublicApi#publicGetLastTradesByInstrumentAndTimeGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PublicApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PublicApi apiInstance = new PublicApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + Integer startTimestamp = 1536569522277; // Integer | The earliest timestamp to return result for + Integer endTimestamp = 1536569522277; // Integer | The most recent timestamp to return result for + Integer count = 56; // Integer | Number of requested items, default - `10` + Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` + String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + try { + Object result = apiInstance.publicGetLastTradesByInstrumentAndTimeGet(instrumentName, startTimestamp, endTimestamp, count, includeOld, sorting); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PublicApi#publicGetLastTradesByInstrumentAndTimeGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -881,6 +1087,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetLastTradesByInstrumentGet** > Object publicGetLastTradesByInstrumentGet(instrumentName, startSeq, endSeq, count, includeOld, sorting) @@ -890,32 +1101,41 @@ Retrieve the latest trades that have occurred for a specific instrument. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PublicApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PublicApi apiInstance = new PublicApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -Integer startSeq = 56; // Integer | The sequence number of the first trade to be returned -Integer endSeq = 56; // Integer | The sequence number of the last trade to be returned -Integer count = 56; // Integer | Number of requested items, default - `10` -Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` -String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) -try { - Object result = apiInstance.publicGetLastTradesByInstrumentGet(instrumentName, startSeq, endSeq, count, includeOld, sorting); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PublicApi#publicGetLastTradesByInstrumentGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PublicApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PublicApi apiInstance = new PublicApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + Integer startSeq = 56; // Integer | The sequence number of the first trade to be returned + Integer endSeq = 56; // Integer | The sequence number of the last trade to be returned + Integer count = 56; // Integer | Number of requested items, default - `10` + Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` + String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + try { + Object result = apiInstance.publicGetLastTradesByInstrumentGet(instrumentName, startSeq, endSeq, count, includeOld, sorting); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PublicApi#publicGetLastTradesByInstrumentGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -943,6 +1163,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetOrderBookGet** > Object publicGetOrderBookGet(instrumentName, depth) @@ -952,28 +1177,37 @@ Retrieves the order book, along with other market values for a given instrument. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PublicApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PublicApi apiInstance = new PublicApi(); -String instrumentName = "instrumentName_example"; // String | The instrument name for which to retrieve the order book, see [`getinstruments`](#getinstruments) to obtain instrument names. -BigDecimal depth = new BigDecimal(); // BigDecimal | The number of entries to return for bids and asks. -try { - Object result = apiInstance.publicGetOrderBookGet(instrumentName, depth); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PublicApi#publicGetOrderBookGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PublicApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PublicApi apiInstance = new PublicApi(defaultClient); + String instrumentName = "instrumentName_example"; // String | The instrument name for which to retrieve the order book, see [`getinstruments`](#getinstruments) to obtain instrument names. + BigDecimal depth = new BigDecimal(); // BigDecimal | The number of entries to return for bids and asks. + try { + Object result = apiInstance.publicGetOrderBookGet(instrumentName, depth); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PublicApi#publicGetOrderBookGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -997,6 +1231,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetTimeGet** > Object publicGetTimeGet() @@ -1006,26 +1245,35 @@ Retrieves the current time (in milliseconds). This API endpoint can be used to c ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PublicApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PublicApi apiInstance = new PublicApi(); -try { - Object result = apiInstance.publicGetTimeGet(); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PublicApi#publicGetTimeGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PublicApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PublicApi apiInstance = new PublicApi(defaultClient); + try { + Object result = apiInstance.publicGetTimeGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PublicApi#publicGetTimeGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1045,6 +1293,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetTradeVolumesGet** > Object publicGetTradeVolumesGet() @@ -1054,26 +1307,35 @@ Retrieves aggregated 24h trade volumes for different instrument types and curren ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PublicApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PublicApi apiInstance = new PublicApi(); -try { - Object result = apiInstance.publicGetTradeVolumesGet(); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PublicApi#publicGetTradeVolumesGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PublicApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PublicApi apiInstance = new PublicApi(defaultClient); + try { + Object result = apiInstance.publicGetTradeVolumesGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PublicApi#publicGetTradeVolumesGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1093,6 +1355,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicGetTradingviewChartDataGet** > Object publicGetTradingviewChartDataGet(instrumentName, startTimestamp, endTimestamp) @@ -1102,29 +1369,38 @@ Publicly available market data used to generate a TradingView candle chart. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PublicApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PublicApi apiInstance = new PublicApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -Integer startTimestamp = 1536569522277; // Integer | The earliest timestamp to return result for -Integer endTimestamp = 1536569522277; // Integer | The most recent timestamp to return result for -try { - Object result = apiInstance.publicGetTradingviewChartDataGet(instrumentName, startTimestamp, endTimestamp); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PublicApi#publicGetTradingviewChartDataGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PublicApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PublicApi apiInstance = new PublicApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + Integer startTimestamp = 1536569522277; // Integer | The earliest timestamp to return result for + Integer endTimestamp = 1536569522277; // Integer | The most recent timestamp to return result for + try { + Object result = apiInstance.publicGetTradingviewChartDataGet(instrumentName, startTimestamp, endTimestamp); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PublicApi#publicGetTradingviewChartDataGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1149,6 +1425,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicTestGet** > Object publicTestGet(expectedResult) @@ -1158,27 +1439,36 @@ Tests the connection to the API server, and returns its version. You can use thi ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PublicApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PublicApi apiInstance = new PublicApi(); -String expectedResult = "expectedResult_example"; // String | The value \"exception\" will trigger an error response. This may be useful for testing wrapper libraries. -try { - Object result = apiInstance.publicTestGet(expectedResult); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PublicApi#publicTestGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PublicApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PublicApi apiInstance = new PublicApi(defaultClient); + String expectedResult = "expectedResult_example"; // String | The value \"exception\" will trigger an error response. This may be useful for testing wrapper libraries. + try { + Object result = apiInstance.publicTestGet(expectedResult); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PublicApi#publicTestGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1201,6 +1491,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicTickerGet** > Object publicTickerGet(instrumentName) @@ -1210,27 +1505,36 @@ Get ticker for an instrument. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PublicApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PublicApi apiInstance = new PublicApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -try { - Object result = apiInstance.publicTickerGet(instrumentName); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PublicApi#publicTickerGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PublicApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PublicApi apiInstance = new PublicApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + try { + Object result = apiInstance.publicTickerGet(instrumentName); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PublicApi#publicTickerGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1253,6 +1557,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **publicValidateFieldGet** > Object publicValidateFieldGet(field, value, value2) @@ -1262,29 +1571,38 @@ Method used to introduce the client software connected to Deribit platform over ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.PublicApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -PublicApi apiInstance = new PublicApi(); -String field = "field_example"; // String | Name of the field to be validated, examples: postal_code, date_of_birth -String value = "value_example"; // String | Value to be checked -String value2 = "value2_example"; // String | Additional value to be compared with -try { - Object result = apiInstance.publicValidateFieldGet(field, value, value2); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling PublicApi#publicValidateFieldGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PublicApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + PublicApi apiInstance = new PublicApi(defaultClient); + String field = "field_example"; // String | Name of the field to be validated, examples: postal_code, date_of_birth + String value = "value_example"; // String | Value to be checked + String value2 = "value2_example"; // String | Additional value to be compared with + try { + Object result = apiInstance.publicValidateFieldGet(field, value, value2); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PublicApi#publicValidateFieldGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1309,3 +1627,8 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + diff --git a/java/docs/SupportingApi.md b/java/docs/SupportingApi.md index b452bbf..14f8f8d 100644 --- a/java/docs/SupportingApi.md +++ b/java/docs/SupportingApi.md @@ -17,26 +17,35 @@ Retrieves the current time (in milliseconds). This API endpoint can be used to c ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.SupportingApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -SupportingApi apiInstance = new SupportingApi(); -try { - Object result = apiInstance.publicGetTimeGet(); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling SupportingApi#publicGetTimeGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.SupportingApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + SupportingApi apiInstance = new SupportingApi(defaultClient); + try { + Object result = apiInstance.publicGetTimeGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling SupportingApi#publicGetTimeGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -56,6 +65,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **publicTestGet** > Object publicTestGet(expectedResult) @@ -65,27 +79,36 @@ Tests the connection to the API server, and returns its version. You can use thi ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.SupportingApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -SupportingApi apiInstance = new SupportingApi(); -String expectedResult = "expectedResult_example"; // String | The value \"exception\" will trigger an error response. This may be useful for testing wrapper libraries. -try { - Object result = apiInstance.publicTestGet(expectedResult); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling SupportingApi#publicTestGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.SupportingApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + SupportingApi apiInstance = new SupportingApi(defaultClient); + String expectedResult = "expectedResult_example"; // String | The value \"exception\" will trigger an error response. This may be useful for testing wrapper libraries. + try { + Object result = apiInstance.publicTestGet(expectedResult); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling SupportingApi#publicTestGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -108,3 +131,8 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + diff --git a/java/docs/TradingApi.md b/java/docs/TradingApi.md index 1218fa6..292f227 100644 --- a/java/docs/TradingApi.md +++ b/java/docs/TradingApi.md @@ -37,38 +37,47 @@ Places a buy order for an instrument. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.TradingApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -TradingApi apiInstance = new TradingApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -BigDecimal amount = new BigDecimal(); // BigDecimal | It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH -String type = "type_example"; // String | The order type, default: `\"limit\"` -String label = "label_example"; // String | user defined label for the order (maximum 32 characters) -BigDecimal price = new BigDecimal(); // BigDecimal |

The order price in base currency (Only for limit and stop_limit orders)

When adding order with advanced=usd, the field price should be the option price value in USD.

When adding order with advanced=implv, the field price should be a value of implied volatility in percentages. For example, price=100, means implied volatility of 100%

-String timeInForce = "good_til_cancelled"; // String |

Specifies how long the order remains in effect. Default `\"good_til_cancelled\"`

  • `\"good_til_cancelled\"` - unfilled order remains in order book until cancelled
  • `\"fill_or_kill\"` - execute a transaction immediately and completely or not at all
  • `\"immediate_or_cancel\"` - execute a transaction immediately, and any portion of the order that cannot be immediately filled is cancelled
-BigDecimal maxShow = new BigDecimal(); // BigDecimal | Maximum amount within an order to be shown to other customers, `0` for invisible order -Boolean postOnly = true; // Boolean |

If true, the order is considered post-only. If the new price would cause the order to be filled immediately (as taker), the price will be changed to be just below the bid.

Only valid in combination with time_in_force=`\"good_til_cancelled\"`

-Boolean reduceOnly = false; // Boolean | If `true`, the order is considered reduce-only which is intended to only reduce a current position -BigDecimal stopPrice = new BigDecimal(); // BigDecimal | Stop price, required for stop limit orders (Only for stop orders) -String trigger = "trigger_example"; // String | Defines trigger type, required for `\"stop_limit\"` order type -String advanced = "advanced_example"; // String | Advanced option order type. (Only for options) -try { - Object result = apiInstance.privateBuyGet(instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling TradingApi#privateBuyGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.TradingApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + TradingApi apiInstance = new TradingApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + BigDecimal amount = new BigDecimal(); // BigDecimal | It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH + String type = "type_example"; // String | The order type, default: `\"limit\"` + String label = "label_example"; // String | user defined label for the order (maximum 32 characters) + BigDecimal price = new BigDecimal(); // BigDecimal |

The order price in base currency (Only for limit and stop_limit orders)

When adding order with advanced=usd, the field price should be the option price value in USD.

When adding order with advanced=implv, the field price should be a value of implied volatility in percentages. For example, price=100, means implied volatility of 100%

+ String timeInForce = "good_til_cancelled"; // String |

Specifies how long the order remains in effect. Default `\"good_til_cancelled\"`

  • `\"good_til_cancelled\"` - unfilled order remains in order book until cancelled
  • `\"fill_or_kill\"` - execute a transaction immediately and completely or not at all
  • `\"immediate_or_cancel\"` - execute a transaction immediately, and any portion of the order that cannot be immediately filled is cancelled
+ BigDecimal maxShow = new BigDecimal(); // BigDecimal | Maximum amount within an order to be shown to other customers, `0` for invisible order + Boolean postOnly = true; // Boolean |

If true, the order is considered post-only. If the new price would cause the order to be filled immediately (as taker), the price will be changed to be just below the bid.

Only valid in combination with time_in_force=`\"good_til_cancelled\"`

+ Boolean reduceOnly = false; // Boolean | If `true`, the order is considered reduce-only which is intended to only reduce a current position + BigDecimal stopPrice = new BigDecimal(); // BigDecimal | Stop price, required for stop limit orders (Only for stop orders) + String trigger = "trigger_example"; // String | Defines trigger type, required for `\"stop_limit\"` order type + String advanced = "advanced_example"; // String | Advanced option order type. (Only for options) + try { + Object result = apiInstance.privateBuyGet(instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling TradingApi#privateBuyGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -102,6 +111,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateCancelAllByCurrencyGet** > Object privateCancelAllByCurrencyGet(currency, kind, type) @@ -111,29 +125,38 @@ Cancels all orders by currency, optionally filtered by instrument kind and/or or ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.TradingApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -TradingApi apiInstance = new TradingApi(); -String currency = "currency_example"; // String | The currency symbol -String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered -String type = "type_example"; // String | Order type - limit, stop or all, default - `all` -try { - Object result = apiInstance.privateCancelAllByCurrencyGet(currency, kind, type); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling TradingApi#privateCancelAllByCurrencyGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.TradingApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + TradingApi apiInstance = new TradingApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered + String type = "type_example"; // String | Order type - limit, stop or all, default - `all` + try { + Object result = apiInstance.privateCancelAllByCurrencyGet(currency, kind, type); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling TradingApi#privateCancelAllByCurrencyGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -158,6 +181,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateCancelAllByInstrumentGet** > Object privateCancelAllByInstrumentGet(instrumentName, type) @@ -167,28 +195,37 @@ Cancels all orders by instrument, optionally filtered by order type. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.TradingApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -TradingApi apiInstance = new TradingApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -String type = "type_example"; // String | Order type - limit, stop or all, default - `all` -try { - Object result = apiInstance.privateCancelAllByInstrumentGet(instrumentName, type); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling TradingApi#privateCancelAllByInstrumentGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.TradingApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + TradingApi apiInstance = new TradingApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + String type = "type_example"; // String | Order type - limit, stop or all, default - `all` + try { + Object result = apiInstance.privateCancelAllByInstrumentGet(instrumentName, type); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling TradingApi#privateCancelAllByInstrumentGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -212,6 +249,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateCancelAllGet** > Object privateCancelAllGet() @@ -221,26 +263,35 @@ This method cancels all users orders and stop orders within all currencies and i ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.TradingApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -TradingApi apiInstance = new TradingApi(); -try { - Object result = apiInstance.privateCancelAllGet(); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling TradingApi#privateCancelAllGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.TradingApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + TradingApi apiInstance = new TradingApi(defaultClient); + try { + Object result = apiInstance.privateCancelAllGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling TradingApi#privateCancelAllGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -260,6 +311,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateCancelGet** > Object privateCancelGet(orderId) @@ -269,27 +325,36 @@ Cancel an order, specified by order id ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.TradingApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -TradingApi apiInstance = new TradingApi(); -String orderId = ETH-100234; // String | The order id -try { - Object result = apiInstance.privateCancelGet(orderId); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling TradingApi#privateCancelGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.TradingApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + TradingApi apiInstance = new TradingApi(defaultClient); + String orderId = ETH-100234; // String | The order id + try { + Object result = apiInstance.privateCancelGet(orderId); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling TradingApi#privateCancelGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -312,6 +377,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateClosePositionGet** > Object privateClosePositionGet(instrumentName, type, price) @@ -321,29 +391,38 @@ Makes closing position reduce only order . ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.TradingApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -TradingApi apiInstance = new TradingApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -String type = "type_example"; // String | The order type -BigDecimal price = new BigDecimal(); // BigDecimal | Optional price for limit order. -try { - Object result = apiInstance.privateClosePositionGet(instrumentName, type, price); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling TradingApi#privateClosePositionGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.TradingApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + TradingApi apiInstance = new TradingApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + String type = "type_example"; // String | The order type + BigDecimal price = new BigDecimal(); // BigDecimal | Optional price for limit order. + try { + Object result = apiInstance.privateClosePositionGet(instrumentName, type, price); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling TradingApi#privateClosePositionGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -368,6 +447,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateEditGet** > Object privateEditGet(orderId, amount, price, postOnly, advanced, stopPrice) @@ -377,32 +461,41 @@ Change price, amount and/or other properties of an order. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.TradingApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -TradingApi apiInstance = new TradingApi(); -String orderId = ETH-100234; // String | The order id -BigDecimal amount = new BigDecimal(); // BigDecimal | It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH -BigDecimal price = new BigDecimal(); // BigDecimal |

The order price in base currency.

When editing an option order with advanced=usd, the field price should be the option price value in USD.

When editing an option order with advanced=implv, the field price should be a value of implied volatility in percentages. For example, price=100, means implied volatility of 100%

-Boolean postOnly = true; // Boolean |

If true, the order is considered post-only. If the new price would cause the order to be filled immediately (as taker), the price will be changed to be just below the bid.

Only valid in combination with time_in_force=`\"good_til_cancelled\"`

-String advanced = "advanced_example"; // String | Advanced option order type. If you have posted an advanced option order, it is necessary to re-supply this parameter when editing it (Only for options) -BigDecimal stopPrice = new BigDecimal(); // BigDecimal | Stop price, required for stop limit orders (Only for stop orders) -try { - Object result = apiInstance.privateEditGet(orderId, amount, price, postOnly, advanced, stopPrice); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling TradingApi#privateEditGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.TradingApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + TradingApi apiInstance = new TradingApi(defaultClient); + String orderId = ETH-100234; // String | The order id + BigDecimal amount = new BigDecimal(); // BigDecimal | It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH + BigDecimal price = new BigDecimal(); // BigDecimal |

The order price in base currency.

When editing an option order with advanced=usd, the field price should be the option price value in USD.

When editing an option order with advanced=implv, the field price should be a value of implied volatility in percentages. For example, price=100, means implied volatility of 100%

+ Boolean postOnly = true; // Boolean |

If true, the order is considered post-only. If the new price would cause the order to be filled immediately (as taker), the price will be changed to be just below the bid.

Only valid in combination with time_in_force=`\"good_til_cancelled\"`

+ String advanced = "advanced_example"; // String | Advanced option order type. If you have posted an advanced option order, it is necessary to re-supply this parameter when editing it (Only for options) + BigDecimal stopPrice = new BigDecimal(); // BigDecimal | Stop price, required for stop limit orders (Only for stop orders) + try { + Object result = apiInstance.privateEditGet(orderId, amount, price, postOnly, advanced, stopPrice); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling TradingApi#privateEditGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -430,6 +523,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetMarginsGet** > Object privateGetMarginsGet(instrumentName, amount, price) @@ -439,29 +537,38 @@ Get margins for given instrument, amount and price. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.TradingApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -TradingApi apiInstance = new TradingApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -BigDecimal amount = 1; // BigDecimal | Amount, integer for future, float for option. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH. -BigDecimal price = new BigDecimal(); // BigDecimal | Price -try { - Object result = apiInstance.privateGetMarginsGet(instrumentName, amount, price); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling TradingApi#privateGetMarginsGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.TradingApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + TradingApi apiInstance = new TradingApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + BigDecimal amount = 1; // BigDecimal | Amount, integer for future, float for option. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH. + BigDecimal price = new BigDecimal(); // BigDecimal | Price + try { + Object result = apiInstance.privateGetMarginsGet(instrumentName, amount, price); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling TradingApi#privateGetMarginsGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -486,6 +593,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetOpenOrdersByCurrencyGet** > Object privateGetOpenOrdersByCurrencyGet(currency, kind, type) @@ -495,29 +607,38 @@ Retrieves list of user's open orders. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.TradingApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -TradingApi apiInstance = new TradingApi(); -String currency = "currency_example"; // String | The currency symbol -String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered -String type = "type_example"; // String | Order type, default - `all` -try { - Object result = apiInstance.privateGetOpenOrdersByCurrencyGet(currency, kind, type); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling TradingApi#privateGetOpenOrdersByCurrencyGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.TradingApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + TradingApi apiInstance = new TradingApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered + String type = "type_example"; // String | Order type, default - `all` + try { + Object result = apiInstance.privateGetOpenOrdersByCurrencyGet(currency, kind, type); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling TradingApi#privateGetOpenOrdersByCurrencyGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -542,6 +663,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetOpenOrdersByInstrumentGet** > Object privateGetOpenOrdersByInstrumentGet(instrumentName, type) @@ -551,28 +677,37 @@ Retrieves list of user's open orders within given Instrument. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.TradingApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -TradingApi apiInstance = new TradingApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -String type = "type_example"; // String | Order type, default - `all` -try { - Object result = apiInstance.privateGetOpenOrdersByInstrumentGet(instrumentName, type); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling TradingApi#privateGetOpenOrdersByInstrumentGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.TradingApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + TradingApi apiInstance = new TradingApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + String type = "type_example"; // String | Order type, default - `all` + try { + Object result = apiInstance.privateGetOpenOrdersByInstrumentGet(instrumentName, type); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling TradingApi#privateGetOpenOrdersByInstrumentGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -596,6 +731,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetOrderHistoryByCurrencyGet** > Object privateGetOrderHistoryByCurrencyGet(currency, kind, count, offset, includeOld, includeUnfilled) @@ -605,32 +745,41 @@ Retrieves history of orders that have been partially or fully filled. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.TradingApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -TradingApi apiInstance = new TradingApi(); -String currency = "currency_example"; // String | The currency symbol -String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered -Integer count = 56; // Integer | Number of requested items, default - `20` -Integer offset = 10; // Integer | The offset for pagination, default - `0` -Boolean includeOld = false; // Boolean | Include in result orders older than 2 days, default - `false` -Boolean includeUnfilled = false; // Boolean | Include in result fully unfilled closed orders, default - `false` -try { - Object result = apiInstance.privateGetOrderHistoryByCurrencyGet(currency, kind, count, offset, includeOld, includeUnfilled); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling TradingApi#privateGetOrderHistoryByCurrencyGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.TradingApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + TradingApi apiInstance = new TradingApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered + Integer count = 56; // Integer | Number of requested items, default - `20` + Integer offset = 10; // Integer | The offset for pagination, default - `0` + Boolean includeOld = false; // Boolean | Include in result orders older than 2 days, default - `false` + Boolean includeUnfilled = false; // Boolean | Include in result fully unfilled closed orders, default - `false` + try { + Object result = apiInstance.privateGetOrderHistoryByCurrencyGet(currency, kind, count, offset, includeOld, includeUnfilled); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling TradingApi#privateGetOrderHistoryByCurrencyGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -658,6 +807,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetOrderHistoryByInstrumentGet** > Object privateGetOrderHistoryByInstrumentGet(instrumentName, count, offset, includeOld, includeUnfilled) @@ -667,31 +821,40 @@ Retrieves history of orders that have been partially or fully filled. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.TradingApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -TradingApi apiInstance = new TradingApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -Integer count = 56; // Integer | Number of requested items, default - `20` -Integer offset = 10; // Integer | The offset for pagination, default - `0` -Boolean includeOld = false; // Boolean | Include in result orders older than 2 days, default - `false` -Boolean includeUnfilled = false; // Boolean | Include in result fully unfilled closed orders, default - `false` -try { - Object result = apiInstance.privateGetOrderHistoryByInstrumentGet(instrumentName, count, offset, includeOld, includeUnfilled); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling TradingApi#privateGetOrderHistoryByInstrumentGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.TradingApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + TradingApi apiInstance = new TradingApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + Integer count = 56; // Integer | Number of requested items, default - `20` + Integer offset = 10; // Integer | The offset for pagination, default - `0` + Boolean includeOld = false; // Boolean | Include in result orders older than 2 days, default - `false` + Boolean includeUnfilled = false; // Boolean | Include in result fully unfilled closed orders, default - `false` + try { + Object result = apiInstance.privateGetOrderHistoryByInstrumentGet(instrumentName, count, offset, includeOld, includeUnfilled); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling TradingApi#privateGetOrderHistoryByInstrumentGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -718,6 +881,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetOrderMarginByIdsGet** > Object privateGetOrderMarginByIdsGet(ids) @@ -727,27 +895,36 @@ Retrieves initial margins of given orders ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.TradingApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -TradingApi apiInstance = new TradingApi(); -List ids = Arrays.asList(); // List | Ids of orders -try { - Object result = apiInstance.privateGetOrderMarginByIdsGet(ids); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling TradingApi#privateGetOrderMarginByIdsGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.TradingApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + TradingApi apiInstance = new TradingApi(defaultClient); + List ids = Arrays.asList(); // List | Ids of orders + try { + Object result = apiInstance.privateGetOrderMarginByIdsGet(ids); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling TradingApi#privateGetOrderMarginByIdsGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -770,6 +947,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetOrderStateGet** > Object privateGetOrderStateGet(orderId) @@ -779,27 +961,36 @@ Retrieve the current state of an order. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.TradingApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -TradingApi apiInstance = new TradingApi(); -String orderId = ETH-100234; // String | The order id -try { - Object result = apiInstance.privateGetOrderStateGet(orderId); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling TradingApi#privateGetOrderStateGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.TradingApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + TradingApi apiInstance = new TradingApi(defaultClient); + String orderId = ETH-100234; // String | The order id + try { + Object result = apiInstance.privateGetOrderStateGet(orderId); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling TradingApi#privateGetOrderStateGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -822,6 +1013,12 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | +**400** | result when used via rest/HTTP | - | + # **privateGetSettlementHistoryByCurrencyGet** > Object privateGetSettlementHistoryByCurrencyGet(currency, type, count) @@ -831,29 +1028,38 @@ Retrieves settlement, delivery and bankruptcy events that have affected your acc ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.TradingApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -TradingApi apiInstance = new TradingApi(); -String currency = "currency_example"; // String | The currency symbol -String type = "type_example"; // String | Settlement type -Integer count = 56; // Integer | Number of requested items, default - `20` -try { - Object result = apiInstance.privateGetSettlementHistoryByCurrencyGet(currency, type, count); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling TradingApi#privateGetSettlementHistoryByCurrencyGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.TradingApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + TradingApi apiInstance = new TradingApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String type = "type_example"; // String | Settlement type + Integer count = 56; // Integer | Number of requested items, default - `20` + try { + Object result = apiInstance.privateGetSettlementHistoryByCurrencyGet(currency, type, count); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling TradingApi#privateGetSettlementHistoryByCurrencyGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -878,6 +1084,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetSettlementHistoryByInstrumentGet** > Object privateGetSettlementHistoryByInstrumentGet(instrumentName, type, count) @@ -887,29 +1098,38 @@ Retrieves public settlement, delivery and bankruptcy events filtered by instrume ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.TradingApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -TradingApi apiInstance = new TradingApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -String type = "type_example"; // String | Settlement type -Integer count = 56; // Integer | Number of requested items, default - `20` -try { - Object result = apiInstance.privateGetSettlementHistoryByInstrumentGet(instrumentName, type, count); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling TradingApi#privateGetSettlementHistoryByInstrumentGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.TradingApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + TradingApi apiInstance = new TradingApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + String type = "type_example"; // String | Settlement type + Integer count = 56; // Integer | Number of requested items, default - `20` + try { + Object result = apiInstance.privateGetSettlementHistoryByInstrumentGet(instrumentName, type, count); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling TradingApi#privateGetSettlementHistoryByInstrumentGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -934,6 +1154,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetUserTradesByCurrencyAndTimeGet** > Object privateGetUserTradesByCurrencyAndTimeGet(currency, startTimestamp, endTimestamp, kind, count, includeOld, sorting) @@ -943,33 +1168,42 @@ Retrieve the latest user trades that have occurred for instruments in a specific ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.TradingApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -TradingApi apiInstance = new TradingApi(); -String currency = "currency_example"; // String | The currency symbol -Integer startTimestamp = 1536569522277; // Integer | The earliest timestamp to return result for -Integer endTimestamp = 1536569522277; // Integer | The most recent timestamp to return result for -String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered -Integer count = 56; // Integer | Number of requested items, default - `10` -Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` -String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) -try { - Object result = apiInstance.privateGetUserTradesByCurrencyAndTimeGet(currency, startTimestamp, endTimestamp, kind, count, includeOld, sorting); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling TradingApi#privateGetUserTradesByCurrencyAndTimeGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.TradingApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + TradingApi apiInstance = new TradingApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + Integer startTimestamp = 1536569522277; // Integer | The earliest timestamp to return result for + Integer endTimestamp = 1536569522277; // Integer | The most recent timestamp to return result for + String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered + Integer count = 56; // Integer | Number of requested items, default - `10` + Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` + String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + try { + Object result = apiInstance.privateGetUserTradesByCurrencyAndTimeGet(currency, startTimestamp, endTimestamp, kind, count, includeOld, sorting); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling TradingApi#privateGetUserTradesByCurrencyAndTimeGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -998,6 +1232,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetUserTradesByCurrencyGet** > Object privateGetUserTradesByCurrencyGet(currency, kind, startId, endId, count, includeOld, sorting) @@ -1007,33 +1246,42 @@ Retrieve the latest user trades that have occurred for instruments in a specific ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.TradingApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -TradingApi apiInstance = new TradingApi(); -String currency = "currency_example"; // String | The currency symbol -String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered -String startId = "startId_example"; // String | The ID number of the first trade to be returned -String endId = "endId_example"; // String | The ID number of the last trade to be returned -Integer count = 56; // Integer | Number of requested items, default - `10` -Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` -String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) -try { - Object result = apiInstance.privateGetUserTradesByCurrencyGet(currency, kind, startId, endId, count, includeOld, sorting); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling TradingApi#privateGetUserTradesByCurrencyGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.TradingApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + TradingApi apiInstance = new TradingApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String kind = "kind_example"; // String | Instrument kind, if not provided instruments of all kinds are considered + String startId = "startId_example"; // String | The ID number of the first trade to be returned + String endId = "endId_example"; // String | The ID number of the last trade to be returned + Integer count = 56; // Integer | Number of requested items, default - `10` + Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` + String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + try { + Object result = apiInstance.privateGetUserTradesByCurrencyGet(currency, kind, startId, endId, count, includeOld, sorting); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling TradingApi#privateGetUserTradesByCurrencyGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1062,6 +1310,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetUserTradesByInstrumentAndTimeGet** > Object privateGetUserTradesByInstrumentAndTimeGet(instrumentName, startTimestamp, endTimestamp, count, includeOld, sorting) @@ -1071,32 +1324,41 @@ Retrieve the latest user trades that have occurred for a specific instrument and ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.TradingApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -TradingApi apiInstance = new TradingApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -Integer startTimestamp = 1536569522277; // Integer | The earliest timestamp to return result for -Integer endTimestamp = 1536569522277; // Integer | The most recent timestamp to return result for -Integer count = 56; // Integer | Number of requested items, default - `10` -Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` -String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) -try { - Object result = apiInstance.privateGetUserTradesByInstrumentAndTimeGet(instrumentName, startTimestamp, endTimestamp, count, includeOld, sorting); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling TradingApi#privateGetUserTradesByInstrumentAndTimeGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.TradingApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + TradingApi apiInstance = new TradingApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + Integer startTimestamp = 1536569522277; // Integer | The earliest timestamp to return result for + Integer endTimestamp = 1536569522277; // Integer | The most recent timestamp to return result for + Integer count = 56; // Integer | Number of requested items, default - `10` + Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` + String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + try { + Object result = apiInstance.privateGetUserTradesByInstrumentAndTimeGet(instrumentName, startTimestamp, endTimestamp, count, includeOld, sorting); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling TradingApi#privateGetUserTradesByInstrumentAndTimeGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1124,6 +1386,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetUserTradesByInstrumentGet** > Object privateGetUserTradesByInstrumentGet(instrumentName, startSeq, endSeq, count, includeOld, sorting) @@ -1133,32 +1400,41 @@ Retrieve the latest user trades that have occurred for a specific instrument. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.TradingApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -TradingApi apiInstance = new TradingApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -Integer startSeq = 56; // Integer | The sequence number of the first trade to be returned -Integer endSeq = 56; // Integer | The sequence number of the last trade to be returned -Integer count = 56; // Integer | Number of requested items, default - `10` -Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` -String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) -try { - Object result = apiInstance.privateGetUserTradesByInstrumentGet(instrumentName, startSeq, endSeq, count, includeOld, sorting); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling TradingApi#privateGetUserTradesByInstrumentGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.TradingApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + TradingApi apiInstance = new TradingApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + Integer startSeq = 56; // Integer | The sequence number of the first trade to be returned + Integer endSeq = 56; // Integer | The sequence number of the last trade to be returned + Integer count = 56; // Integer | Number of requested items, default - `10` + Boolean includeOld = true; // Boolean | Include trades older than 7 days, default - `false` + String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + try { + Object result = apiInstance.privateGetUserTradesByInstrumentGet(instrumentName, startSeq, endSeq, count, includeOld, sorting); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling TradingApi#privateGetUserTradesByInstrumentGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1186,6 +1462,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetUserTradesByOrderGet** > Object privateGetUserTradesByOrderGet(orderId, sorting) @@ -1195,28 +1476,37 @@ Retrieve the list of user trades that was created for given order ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.TradingApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -TradingApi apiInstance = new TradingApi(); -String orderId = ETH-100234; // String | The order id -String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) -try { - Object result = apiInstance.privateGetUserTradesByOrderGet(orderId, sorting); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling TradingApi#privateGetUserTradesByOrderGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.TradingApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + TradingApi apiInstance = new TradingApi(defaultClient); + String orderId = ETH-100234; // String | The order id + String sorting = "sorting_example"; // String | Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + try { + Object result = apiInstance.privateGetUserTradesByOrderGet(orderId, sorting); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling TradingApi#privateGetUserTradesByOrderGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1240,6 +1530,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateSellGet** > Object privateSellGet(instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced) @@ -1249,38 +1544,47 @@ Places a sell order for an instrument. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.TradingApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -TradingApi apiInstance = new TradingApi(); -String instrumentName = BTC-PERPETUAL; // String | Instrument name -BigDecimal amount = new BigDecimal(); // BigDecimal | It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH -String type = "type_example"; // String | The order type, default: `\"limit\"` -String label = "label_example"; // String | user defined label for the order (maximum 32 characters) -BigDecimal price = new BigDecimal(); // BigDecimal |

The order price in base currency (Only for limit and stop_limit orders)

When adding order with advanced=usd, the field price should be the option price value in USD.

When adding order with advanced=implv, the field price should be a value of implied volatility in percentages. For example, price=100, means implied volatility of 100%

-String timeInForce = "good_til_cancelled"; // String |

Specifies how long the order remains in effect. Default `\"good_til_cancelled\"`

  • `\"good_til_cancelled\"` - unfilled order remains in order book until cancelled
  • `\"fill_or_kill\"` - execute a transaction immediately and completely or not at all
  • `\"immediate_or_cancel\"` - execute a transaction immediately, and any portion of the order that cannot be immediately filled is cancelled
-BigDecimal maxShow = new BigDecimal(); // BigDecimal | Maximum amount within an order to be shown to other customers, `0` for invisible order -Boolean postOnly = true; // Boolean |

If true, the order is considered post-only. If the new price would cause the order to be filled immediately (as taker), the price will be changed to be just below the bid.

Only valid in combination with time_in_force=`\"good_til_cancelled\"`

-Boolean reduceOnly = false; // Boolean | If `true`, the order is considered reduce-only which is intended to only reduce a current position -BigDecimal stopPrice = new BigDecimal(); // BigDecimal | Stop price, required for stop limit orders (Only for stop orders) -String trigger = "trigger_example"; // String | Defines trigger type, required for `\"stop_limit\"` order type -String advanced = "advanced_example"; // String | Advanced option order type. (Only for options) -try { - Object result = apiInstance.privateSellGet(instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling TradingApi#privateSellGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.TradingApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + TradingApi apiInstance = new TradingApi(defaultClient); + String instrumentName = BTC-PERPETUAL; // String | Instrument name + BigDecimal amount = new BigDecimal(); // BigDecimal | It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH + String type = "type_example"; // String | The order type, default: `\"limit\"` + String label = "label_example"; // String | user defined label for the order (maximum 32 characters) + BigDecimal price = new BigDecimal(); // BigDecimal |

The order price in base currency (Only for limit and stop_limit orders)

When adding order with advanced=usd, the field price should be the option price value in USD.

When adding order with advanced=implv, the field price should be a value of implied volatility in percentages. For example, price=100, means implied volatility of 100%

+ String timeInForce = "good_til_cancelled"; // String |

Specifies how long the order remains in effect. Default `\"good_til_cancelled\"`

  • `\"good_til_cancelled\"` - unfilled order remains in order book until cancelled
  • `\"fill_or_kill\"` - execute a transaction immediately and completely or not at all
  • `\"immediate_or_cancel\"` - execute a transaction immediately, and any portion of the order that cannot be immediately filled is cancelled
+ BigDecimal maxShow = new BigDecimal(); // BigDecimal | Maximum amount within an order to be shown to other customers, `0` for invisible order + Boolean postOnly = true; // Boolean |

If true, the order is considered post-only. If the new price would cause the order to be filled immediately (as taker), the price will be changed to be just below the bid.

Only valid in combination with time_in_force=`\"good_til_cancelled\"`

+ Boolean reduceOnly = false; // Boolean | If `true`, the order is considered reduce-only which is intended to only reduce a current position + BigDecimal stopPrice = new BigDecimal(); // BigDecimal | Stop price, required for stop limit orders (Only for stop orders) + String trigger = "trigger_example"; // String | Defines trigger type, required for `\"stop_limit\"` order type + String advanced = "advanced_example"; // String | Advanced option order type. (Only for options) + try { + Object result = apiInstance.privateSellGet(instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling TradingApi#privateSellGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -1314,3 +1618,8 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + diff --git a/java/docs/WalletApi.md b/java/docs/WalletApi.md index f1c2c8e..ea6872f 100644 --- a/java/docs/WalletApi.md +++ b/java/docs/WalletApi.md @@ -29,31 +29,40 @@ Adds new entry to address book of given type ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.WalletApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -WalletApi apiInstance = new WalletApi(); -String currency = "currency_example"; // String | The currency symbol -String type = "type_example"; // String | Address book type -String address = "address_example"; // String | Address in currency format, it must be in address book -String name = Main address; // String | Name of address book entry -String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account -try { - Object result = apiInstance.privateAddToAddressBookGet(currency, type, address, name, tfa); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling WalletApi#privateAddToAddressBookGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.WalletApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + WalletApi apiInstance = new WalletApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String type = "type_example"; // String | Address book type + String address = "address_example"; // String | Address in currency format, it must be in address book + String name = Main address; // String | Name of address book entry + String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account + try { + Object result = apiInstance.privateAddToAddressBookGet(currency, type, address, name, tfa); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling WalletApi#privateAddToAddressBookGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -80,6 +89,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateCancelTransferByIdGet** > Object privateCancelTransferByIdGet(currency, id, tfa) @@ -89,29 +103,38 @@ Cancel transfer ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.WalletApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -WalletApi apiInstance = new WalletApi(); -String currency = "currency_example"; // String | The currency symbol -Integer id = 12; // Integer | Id of transfer -String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account -try { - Object result = apiInstance.privateCancelTransferByIdGet(currency, id, tfa); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling WalletApi#privateCancelTransferByIdGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.WalletApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + WalletApi apiInstance = new WalletApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + Integer id = 12; // Integer | Id of transfer + String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account + try { + Object result = apiInstance.privateCancelTransferByIdGet(currency, id, tfa); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling WalletApi#privateCancelTransferByIdGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -136,6 +159,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateCancelWithdrawalGet** > Object privateCancelWithdrawalGet(currency, id) @@ -145,28 +173,37 @@ Cancels withdrawal request ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.WalletApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -WalletApi apiInstance = new WalletApi(); -String currency = "currency_example"; // String | The currency symbol -BigDecimal id = 1; // BigDecimal | The withdrawal id -try { - Object result = apiInstance.privateCancelWithdrawalGet(currency, id); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling WalletApi#privateCancelWithdrawalGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.WalletApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + WalletApi apiInstance = new WalletApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + BigDecimal id = 1; // BigDecimal | The withdrawal id + try { + Object result = apiInstance.privateCancelWithdrawalGet(currency, id); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling WalletApi#privateCancelWithdrawalGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -190,6 +227,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateCreateDepositAddressGet** > Object privateCreateDepositAddressGet(currency) @@ -199,27 +241,36 @@ Creates deposit address in currency ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.WalletApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -WalletApi apiInstance = new WalletApi(); -String currency = "currency_example"; // String | The currency symbol -try { - Object result = apiInstance.privateCreateDepositAddressGet(currency); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling WalletApi#privateCreateDepositAddressGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.WalletApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + WalletApi apiInstance = new WalletApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + try { + Object result = apiInstance.privateCreateDepositAddressGet(currency); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling WalletApi#privateCreateDepositAddressGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -242,6 +293,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetAddressBookGet** > Object privateGetAddressBookGet(currency, type) @@ -251,28 +307,37 @@ Retrieves address book of given type ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.WalletApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -WalletApi apiInstance = new WalletApi(); -String currency = "currency_example"; // String | The currency symbol -String type = "type_example"; // String | Address book type -try { - Object result = apiInstance.privateGetAddressBookGet(currency, type); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling WalletApi#privateGetAddressBookGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.WalletApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + WalletApi apiInstance = new WalletApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String type = "type_example"; // String | Address book type + try { + Object result = apiInstance.privateGetAddressBookGet(currency, type); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling WalletApi#privateGetAddressBookGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -296,6 +361,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetCurrentDepositAddressGet** > Object privateGetCurrentDepositAddressGet(currency) @@ -305,27 +375,36 @@ Retrieve deposit address for currency ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.WalletApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -WalletApi apiInstance = new WalletApi(); -String currency = "currency_example"; // String | The currency symbol -try { - Object result = apiInstance.privateGetCurrentDepositAddressGet(currency); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling WalletApi#privateGetCurrentDepositAddressGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.WalletApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + WalletApi apiInstance = new WalletApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + try { + Object result = apiInstance.privateGetCurrentDepositAddressGet(currency); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling WalletApi#privateGetCurrentDepositAddressGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -348,6 +427,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetDepositsGet** > Object privateGetDepositsGet(currency, count, offset) @@ -357,29 +441,38 @@ Retrieve the latest users deposits ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.WalletApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -WalletApi apiInstance = new WalletApi(); -String currency = "currency_example"; // String | The currency symbol -Integer count = 56; // Integer | Number of requested items, default - `10` -Integer offset = 10; // Integer | The offset for pagination, default - `0` -try { - Object result = apiInstance.privateGetDepositsGet(currency, count, offset); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling WalletApi#privateGetDepositsGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.WalletApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + WalletApi apiInstance = new WalletApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + Integer count = 56; // Integer | Number of requested items, default - `10` + Integer offset = 10; // Integer | The offset for pagination, default - `0` + try { + Object result = apiInstance.privateGetDepositsGet(currency, count, offset); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling WalletApi#privateGetDepositsGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -404,6 +497,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetTransfersGet** > Object privateGetTransfersGet(currency, count, offset) @@ -413,29 +511,38 @@ Adds new entry to address book of given type ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.WalletApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -WalletApi apiInstance = new WalletApi(); -String currency = "currency_example"; // String | The currency symbol -Integer count = 56; // Integer | Number of requested items, default - `10` -Integer offset = 10; // Integer | The offset for pagination, default - `0` -try { - Object result = apiInstance.privateGetTransfersGet(currency, count, offset); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling WalletApi#privateGetTransfersGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.WalletApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + WalletApi apiInstance = new WalletApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + Integer count = 56; // Integer | Number of requested items, default - `10` + Integer offset = 10; // Integer | The offset for pagination, default - `0` + try { + Object result = apiInstance.privateGetTransfersGet(currency, count, offset); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling WalletApi#privateGetTransfersGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -460,6 +567,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateGetWithdrawalsGet** > Object privateGetWithdrawalsGet(currency, count, offset) @@ -469,29 +581,38 @@ Retrieve the latest users withdrawals ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.WalletApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -WalletApi apiInstance = new WalletApi(); -String currency = "currency_example"; // String | The currency symbol -Integer count = 56; // Integer | Number of requested items, default - `10` -Integer offset = 10; // Integer | The offset for pagination, default - `0` -try { - Object result = apiInstance.privateGetWithdrawalsGet(currency, count, offset); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling WalletApi#privateGetWithdrawalsGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.WalletApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + WalletApi apiInstance = new WalletApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + Integer count = 56; // Integer | Number of requested items, default - `10` + Integer offset = 10; // Integer | The offset for pagination, default - `0` + try { + Object result = apiInstance.privateGetWithdrawalsGet(currency, count, offset); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling WalletApi#privateGetWithdrawalsGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -516,6 +637,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateRemoveFromAddressBookGet** > Object privateRemoveFromAddressBookGet(currency, type, address, tfa) @@ -525,30 +651,39 @@ Adds new entry to address book of given type ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.WalletApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -WalletApi apiInstance = new WalletApi(); -String currency = "currency_example"; // String | The currency symbol -String type = "type_example"; // String | Address book type -String address = "address_example"; // String | Address in currency format, it must be in address book -String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account -try { - Object result = apiInstance.privateRemoveFromAddressBookGet(currency, type, address, tfa); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling WalletApi#privateRemoveFromAddressBookGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.WalletApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + WalletApi apiInstance = new WalletApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String type = "type_example"; // String | Address book type + String address = "address_example"; // String | Address in currency format, it must be in address book + String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account + try { + Object result = apiInstance.privateRemoveFromAddressBookGet(currency, type, address, tfa); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling WalletApi#privateRemoveFromAddressBookGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -574,6 +709,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateSubmitTransferToSubaccountGet** > Object privateSubmitTransferToSubaccountGet(currency, amount, destination) @@ -583,29 +723,38 @@ Transfer funds to a subaccount. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.WalletApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -WalletApi apiInstance = new WalletApi(); -String currency = "currency_example"; // String | The currency symbol -BigDecimal amount = new BigDecimal(); // BigDecimal | Amount of funds to be transferred -Integer destination = 1; // Integer | Id of destination subaccount -try { - Object result = apiInstance.privateSubmitTransferToSubaccountGet(currency, amount, destination); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling WalletApi#privateSubmitTransferToSubaccountGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.WalletApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + WalletApi apiInstance = new WalletApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + BigDecimal amount = new BigDecimal(); // BigDecimal | Amount of funds to be transferred + Integer destination = 1; // Integer | Id of destination subaccount + try { + Object result = apiInstance.privateSubmitTransferToSubaccountGet(currency, amount, destination); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling WalletApi#privateSubmitTransferToSubaccountGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -630,6 +779,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + # **privateSubmitTransferToUserGet** > Object privateSubmitTransferToUserGet(currency, amount, destination, tfa) @@ -639,30 +793,39 @@ Transfer funds to a another user. ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.WalletApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -WalletApi apiInstance = new WalletApi(); -String currency = "currency_example"; // String | The currency symbol -BigDecimal amount = new BigDecimal(); // BigDecimal | Amount of funds to be transferred -String destination = "destination_example"; // String | Destination address from address book -String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account -try { - Object result = apiInstance.privateSubmitTransferToUserGet(currency, amount, destination, tfa); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling WalletApi#privateSubmitTransferToUserGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.WalletApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + WalletApi apiInstance = new WalletApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + BigDecimal amount = new BigDecimal(); // BigDecimal | Amount of funds to be transferred + String destination = "destination_example"; // String | Destination address from address book + String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account + try { + Object result = apiInstance.privateSubmitTransferToUserGet(currency, amount, destination, tfa); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling WalletApi#privateSubmitTransferToUserGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -688,6 +851,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateToggleDepositAddressCreationGet** > Object privateToggleDepositAddressCreationGet(currency, state) @@ -697,28 +865,37 @@ Enable or disable deposit address creation ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.WalletApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -WalletApi apiInstance = new WalletApi(); -String currency = "currency_example"; // String | The currency symbol -Boolean state = true; // Boolean | -try { - Object result = apiInstance.privateToggleDepositAddressCreationGet(currency, state); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling WalletApi#privateToggleDepositAddressCreationGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.WalletApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + WalletApi apiInstance = new WalletApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + Boolean state = true; // Boolean | + try { + Object result = apiInstance.privateToggleDepositAddressCreationGet(currency, state); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling WalletApi#privateToggleDepositAddressCreationGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -742,6 +919,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + # **privateWithdrawGet** > Object privateWithdrawGet(currency, address, amount, priority, tfa) @@ -751,31 +933,40 @@ Creates a new withdrawal request ### Example ```java // Import classes: -//import org.openapitools.client.ApiClient; -//import org.openapitools.client.ApiException; -//import org.openapitools.client.Configuration; -//import org.openapitools.client.auth.*; -//import org.openapitools.client.api.WalletApi; - -ApiClient defaultClient = Configuration.getDefaultApiClient(); - -// Configure HTTP basic authorization: bearerAuth -HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); -bearerAuth.setUsername("YOUR USERNAME"); -bearerAuth.setPassword("YOUR PASSWORD"); - -WalletApi apiInstance = new WalletApi(); -String currency = "currency_example"; // String | The currency symbol -String address = "address_example"; // String | Address in currency format, it must be in address book -BigDecimal amount = new BigDecimal(); // BigDecimal | Amount of funds to be withdrawn -String priority = "priority_example"; // String | Withdrawal priority, optional for BTC, default: `high` -String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account -try { - Object result = apiInstance.privateWithdrawGet(currency, address, amount, priority, tfa); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling WalletApi#privateWithdrawGet"); - e.printStackTrace(); +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.WalletApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("https://www.deribit.com/api/v2"); + + // Configure HTTP basic authorization: bearerAuth + HttpBasicAuth bearerAuth = (HttpBasicAuth) defaultClient.getAuthentication("bearerAuth"); + bearerAuth.setUsername("YOUR USERNAME"); + bearerAuth.setPassword("YOUR PASSWORD"); + + WalletApi apiInstance = new WalletApi(defaultClient); + String currency = "currency_example"; // String | The currency symbol + String address = "address_example"; // String | Address in currency format, it must be in address book + BigDecimal amount = new BigDecimal(); // BigDecimal | Amount of funds to be withdrawn + String priority = "priority_example"; // String | Withdrawal priority, optional for BTC, default: `high` + String tfa = "tfa_example"; // String | TFA code, required when TFA is enabled for current account + try { + Object result = apiInstance.privateWithdrawGet(currency, address, amount, priority, tfa); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling WalletApi#privateWithdrawGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } } ``` @@ -802,3 +993,8 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + diff --git a/java/src/main/java/org/openapitools/client/ApiCallback.java b/java/src/main/java/org/openapitools/client/ApiCallback.java index 0b12353..f8a94f3 100644 --- a/java/src/main/java/org/openapitools/client/ApiCallback.java +++ b/java/src/main/java/org/openapitools/client/ApiCallback.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/java/src/main/java/org/openapitools/client/ApiClient.java b/java/src/main/java/org/openapitools/client/ApiClient.java index 102e4ca..515654d 100644 --- a/java/src/main/java/org/openapitools/client/ApiClient.java +++ b/java/src/main/java/org/openapitools/client/ApiClient.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -95,7 +95,7 @@ private void init() { json = new JSON(); // Set default User-Agent. - setUserAgent("OpenAPI-Generator/1.0.0/java"); + setUserAgent("OpenAPI-Generator/2.0.0/java"); authentications = new HashMap(); } diff --git a/java/src/main/java/org/openapitools/client/ApiException.java b/java/src/main/java/org/openapitools/client/ApiException.java index 19cc0c1..98ff8cb 100644 --- a/java/src/main/java/org/openapitools/client/ApiException.java +++ b/java/src/main/java/org/openapitools/client/ApiException.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -16,7 +16,7 @@ import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class ApiException extends Exception { private int code = 0; private Map> responseHeaders = null; diff --git a/java/src/main/java/org/openapitools/client/ApiResponse.java b/java/src/main/java/org/openapitools/client/ApiResponse.java index add3931..edd0a12 100644 --- a/java/src/main/java/org/openapitools/client/ApiResponse.java +++ b/java/src/main/java/org/openapitools/client/ApiResponse.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/java/src/main/java/org/openapitools/client/Configuration.java b/java/src/main/java/org/openapitools/client/Configuration.java index 0108e15..8b92e33 100644 --- a/java/src/main/java/org/openapitools/client/Configuration.java +++ b/java/src/main/java/org/openapitools/client/Configuration.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -13,7 +13,7 @@ package org.openapitools.client; -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class Configuration { private static ApiClient defaultApiClient = new ApiClient(); diff --git a/java/src/main/java/org/openapitools/client/GzipRequestInterceptor.java b/java/src/main/java/org/openapitools/client/GzipRequestInterceptor.java index ba0a6a7..c423e73 100644 --- a/java/src/main/java/org/openapitools/client/GzipRequestInterceptor.java +++ b/java/src/main/java/org/openapitools/client/GzipRequestInterceptor.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/java/src/main/java/org/openapitools/client/JSON.java b/java/src/main/java/org/openapitools/client/JSON.java index 59ff8c6..651804b 100644 --- a/java/src/main/java/org/openapitools/client/JSON.java +++ b/java/src/main/java/org/openapitools/client/JSON.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/java/src/main/java/org/openapitools/client/Pair.java b/java/src/main/java/org/openapitools/client/Pair.java index a135fbb..b201f6e 100644 --- a/java/src/main/java/org/openapitools/client/Pair.java +++ b/java/src/main/java/org/openapitools/client/Pair.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -13,7 +13,7 @@ package org.openapitools.client; -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class Pair { private String name = ""; private String value = ""; diff --git a/java/src/main/java/org/openapitools/client/ProgressRequestBody.java b/java/src/main/java/org/openapitools/client/ProgressRequestBody.java index 040150a..d11087c 100644 --- a/java/src/main/java/org/openapitools/client/ProgressRequestBody.java +++ b/java/src/main/java/org/openapitools/client/ProgressRequestBody.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/java/src/main/java/org/openapitools/client/ProgressResponseBody.java b/java/src/main/java/org/openapitools/client/ProgressResponseBody.java index 563d295..194461d 100644 --- a/java/src/main/java/org/openapitools/client/ProgressResponseBody.java +++ b/java/src/main/java/org/openapitools/client/ProgressResponseBody.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/java/src/main/java/org/openapitools/client/StringUtil.java b/java/src/main/java/org/openapitools/client/StringUtil.java index 54fb174..e99c15b 100644 --- a/java/src/main/java/org/openapitools/client/StringUtil.java +++ b/java/src/main/java/org/openapitools/client/StringUtil.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -13,7 +13,7 @@ package org.openapitools.client; -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/java/src/main/java/org/openapitools/client/api/AccountManagementApi.java b/java/src/main/java/org/openapitools/client/api/AccountManagementApi.java index c34598e..884c2ce 100644 --- a/java/src/main/java/org/openapitools/client/api/AccountManagementApi.java +++ b/java/src/main/java/org/openapitools/client/api/AccountManagementApi.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -61,6 +61,11 @@ public void setApiClient(ApiClient apiClient) { * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateChangeSubaccountNameGetCall(Integer sid, String name, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -124,6 +129,11 @@ private okhttp3.Call privateChangeSubaccountNameGetValidateBeforeCall(Integer si * @param name The new user name (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateChangeSubaccountNameGet(Integer sid, String name) throws ApiException { ApiResponse localVarResp = privateChangeSubaccountNameGetWithHttpInfo(sid, name); @@ -137,6 +147,11 @@ public Object privateChangeSubaccountNameGet(Integer sid, String name) throws Ap * @param name The new user name (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateChangeSubaccountNameGetWithHttpInfo(Integer sid, String name) throws ApiException { okhttp3.Call localVarCall = privateChangeSubaccountNameGetValidateBeforeCall(sid, name, null); @@ -152,6 +167,11 @@ public ApiResponse privateChangeSubaccountNameGetWithHttpInfo(Integer si * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateChangeSubaccountNameGetAsync(Integer sid, String name, final ApiCallback _callback) throws ApiException { @@ -165,6 +185,11 @@ public okhttp3.Call privateChangeSubaccountNameGetAsync(Integer sid, String name * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateCreateSubaccountGetCall(final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -208,6 +233,11 @@ private okhttp3.Call privateCreateSubaccountGetValidateBeforeCall(final ApiCallb * * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateCreateSubaccountGet() throws ApiException { ApiResponse localVarResp = privateCreateSubaccountGetWithHttpInfo(); @@ -219,6 +249,11 @@ public Object privateCreateSubaccountGet() throws ApiException { * * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateCreateSubaccountGetWithHttpInfo() throws ApiException { okhttp3.Call localVarCall = privateCreateSubaccountGetValidateBeforeCall(null); @@ -232,6 +267,11 @@ public ApiResponse privateCreateSubaccountGetWithHttpInfo() throws ApiEx * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateCreateSubaccountGetAsync(final ApiCallback _callback) throws ApiException { @@ -246,6 +286,11 @@ public okhttp3.Call privateCreateSubaccountGetAsync(final ApiCallback _c * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateDisableTfaForSubaccountGetCall(Integer sid, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -299,6 +344,11 @@ private okhttp3.Call privateDisableTfaForSubaccountGetValidateBeforeCall(Integer * @param sid The user id for the subaccount (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateDisableTfaForSubaccountGet(Integer sid) throws ApiException { ApiResponse localVarResp = privateDisableTfaForSubaccountGetWithHttpInfo(sid); @@ -311,6 +361,11 @@ public Object privateDisableTfaForSubaccountGet(Integer sid) throws ApiException * @param sid The user id for the subaccount (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateDisableTfaForSubaccountGetWithHttpInfo(Integer sid) throws ApiException { okhttp3.Call localVarCall = privateDisableTfaForSubaccountGetValidateBeforeCall(sid, null); @@ -325,6 +380,11 @@ public ApiResponse privateDisableTfaForSubaccountGetWithHttpInfo(Integer * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateDisableTfaForSubaccountGetAsync(Integer sid, final ApiCallback _callback) throws ApiException { @@ -340,6 +400,11 @@ public okhttp3.Call privateDisableTfaForSubaccountGetAsync(Integer sid, final Ap * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetAccountSummaryGetCall(String currency, Boolean extended, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -398,6 +463,11 @@ private okhttp3.Call privateGetAccountSummaryGetValidateBeforeCall(String curren * @param extended Include additional fields (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetAccountSummaryGet(String currency, Boolean extended) throws ApiException { ApiResponse localVarResp = privateGetAccountSummaryGetWithHttpInfo(currency, extended); @@ -411,6 +481,11 @@ public Object privateGetAccountSummaryGet(String currency, Boolean extended) thr * @param extended Include additional fields (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetAccountSummaryGetWithHttpInfo(String currency, Boolean extended) throws ApiException { okhttp3.Call localVarCall = privateGetAccountSummaryGetValidateBeforeCall(currency, extended, null); @@ -426,6 +501,11 @@ public ApiResponse privateGetAccountSummaryGetWithHttpInfo(String curren * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetAccountSummaryGetAsync(String currency, Boolean extended, final ApiCallback _callback) throws ApiException { @@ -439,6 +519,11 @@ public okhttp3.Call privateGetAccountSummaryGetAsync(String currency, Boolean ex * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetEmailLanguageGetCall(final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -482,6 +567,11 @@ private okhttp3.Call privateGetEmailLanguageGetValidateBeforeCall(final ApiCallb * * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetEmailLanguageGet() throws ApiException { ApiResponse localVarResp = privateGetEmailLanguageGetWithHttpInfo(); @@ -493,6 +583,11 @@ public Object privateGetEmailLanguageGet() throws ApiException { * * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetEmailLanguageGetWithHttpInfo() throws ApiException { okhttp3.Call localVarCall = privateGetEmailLanguageGetValidateBeforeCall(null); @@ -506,6 +601,11 @@ public ApiResponse privateGetEmailLanguageGetWithHttpInfo() throws ApiEx * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetEmailLanguageGetAsync(final ApiCallback _callback) throws ApiException { @@ -519,6 +619,11 @@ public okhttp3.Call privateGetEmailLanguageGetAsync(final ApiCallback _c * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetNewAnnouncementsGetCall(final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -562,6 +667,11 @@ private okhttp3.Call privateGetNewAnnouncementsGetValidateBeforeCall(final ApiCa * * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetNewAnnouncementsGet() throws ApiException { ApiResponse localVarResp = privateGetNewAnnouncementsGetWithHttpInfo(); @@ -573,6 +683,11 @@ public Object privateGetNewAnnouncementsGet() throws ApiException { * * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetNewAnnouncementsGetWithHttpInfo() throws ApiException { okhttp3.Call localVarCall = privateGetNewAnnouncementsGetValidateBeforeCall(null); @@ -586,6 +701,11 @@ public ApiResponse privateGetNewAnnouncementsGetWithHttpInfo() throws Ap * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetNewAnnouncementsGetAsync(final ApiCallback _callback) throws ApiException { @@ -600,6 +720,12 @@ public okhttp3.Call privateGetNewAnnouncementsGetAsync(final ApiCallback * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + +
Status Code Description Response Headers
200 When successful returns position -
400 When some error occurs -
*/ public okhttp3.Call privateGetPositionGetCall(String instrumentName, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -653,6 +779,12 @@ private okhttp3.Call privateGetPositionGetValidateBeforeCall(String instrumentNa * @param instrumentName Instrument name (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
Status Code Description Response Headers
200 When successful returns position -
400 When some error occurs -
*/ public Object privateGetPositionGet(String instrumentName) throws ApiException { ApiResponse localVarResp = privateGetPositionGetWithHttpInfo(instrumentName); @@ -665,6 +797,12 @@ public Object privateGetPositionGet(String instrumentName) throws ApiException { * @param instrumentName Instrument name (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
Status Code Description Response Headers
200 When successful returns position -
400 When some error occurs -
*/ public ApiResponse privateGetPositionGetWithHttpInfo(String instrumentName) throws ApiException { okhttp3.Call localVarCall = privateGetPositionGetValidateBeforeCall(instrumentName, null); @@ -679,6 +817,12 @@ public ApiResponse privateGetPositionGetWithHttpInfo(String instrumentNa * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + +
Status Code Description Response Headers
200 When successful returns position -
400 When some error occurs -
*/ public okhttp3.Call privateGetPositionGetAsync(String instrumentName, final ApiCallback _callback) throws ApiException { @@ -694,6 +838,12 @@ public okhttp3.Call privateGetPositionGetAsync(String instrumentName, final ApiC * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + +
Status Code Description Response Headers
200 When successful returns array of positions -
400 When some error occurs -
*/ public okhttp3.Call privateGetPositionsGetCall(String currency, String kind, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -752,6 +902,12 @@ private okhttp3.Call privateGetPositionsGetValidateBeforeCall(String currency, S * @param kind Kind filter on positions (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
Status Code Description Response Headers
200 When successful returns array of positions -
400 When some error occurs -
*/ public Object privateGetPositionsGet(String currency, String kind) throws ApiException { ApiResponse localVarResp = privateGetPositionsGetWithHttpInfo(currency, kind); @@ -765,6 +921,12 @@ public Object privateGetPositionsGet(String currency, String kind) throws ApiExc * @param kind Kind filter on positions (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
Status Code Description Response Headers
200 When successful returns array of positions -
400 When some error occurs -
*/ public ApiResponse privateGetPositionsGetWithHttpInfo(String currency, String kind) throws ApiException { okhttp3.Call localVarCall = privateGetPositionsGetValidateBeforeCall(currency, kind, null); @@ -780,6 +942,12 @@ public ApiResponse privateGetPositionsGetWithHttpInfo(String currency, S * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + +
Status Code Description Response Headers
200 When successful returns array of positions -
400 When some error occurs -
*/ public okhttp3.Call privateGetPositionsGetAsync(String currency, String kind, final ApiCallback _callback) throws ApiException { @@ -794,6 +962,12 @@ public okhttp3.Call privateGetPositionsGetAsync(String currency, String kind, fi * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + +
Status Code Description Response Headers
200 ok response -
401 not authorised -
*/ public okhttp3.Call privateGetSubaccountsGetCall(Boolean withPortfolio, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -842,6 +1016,12 @@ private okhttp3.Call privateGetSubaccountsGetValidateBeforeCall(Boolean withPort * @param withPortfolio (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
Status Code Description Response Headers
200 ok response -
401 not authorised -
*/ public Object privateGetSubaccountsGet(Boolean withPortfolio) throws ApiException { ApiResponse localVarResp = privateGetSubaccountsGetWithHttpInfo(withPortfolio); @@ -854,6 +1034,12 @@ public Object privateGetSubaccountsGet(Boolean withPortfolio) throws ApiExceptio * @param withPortfolio (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
Status Code Description Response Headers
200 ok response -
401 not authorised -
*/ public ApiResponse privateGetSubaccountsGetWithHttpInfo(Boolean withPortfolio) throws ApiException { okhttp3.Call localVarCall = privateGetSubaccountsGetValidateBeforeCall(withPortfolio, null); @@ -868,6 +1054,12 @@ public ApiResponse privateGetSubaccountsGetWithHttpInfo(Boolean withPort * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + +
Status Code Description Response Headers
200 ok response -
401 not authorised -
*/ public okhttp3.Call privateGetSubaccountsGetAsync(Boolean withPortfolio, final ApiCallback _callback) throws ApiException { @@ -882,6 +1074,11 @@ public okhttp3.Call privateGetSubaccountsGetAsync(Boolean withPortfolio, final A * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateSetAnnouncementAsReadGetCall(BigDecimal announcementId, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -935,6 +1132,11 @@ private okhttp3.Call privateSetAnnouncementAsReadGetValidateBeforeCall(BigDecima * @param announcementId the ID of the announcement (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateSetAnnouncementAsReadGet(BigDecimal announcementId) throws ApiException { ApiResponse localVarResp = privateSetAnnouncementAsReadGetWithHttpInfo(announcementId); @@ -947,6 +1149,11 @@ public Object privateSetAnnouncementAsReadGet(BigDecimal announcementId) throws * @param announcementId the ID of the announcement (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateSetAnnouncementAsReadGetWithHttpInfo(BigDecimal announcementId) throws ApiException { okhttp3.Call localVarCall = privateSetAnnouncementAsReadGetValidateBeforeCall(announcementId, null); @@ -961,6 +1168,11 @@ public ApiResponse privateSetAnnouncementAsReadGetWithHttpInfo(BigDecima * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateSetAnnouncementAsReadGetAsync(BigDecimal announcementId, final ApiCallback _callback) throws ApiException { @@ -976,6 +1188,11 @@ public okhttp3.Call privateSetAnnouncementAsReadGetAsync(BigDecimal announcement * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateSetEmailForSubaccountGetCall(Integer sid, String email, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1039,6 +1256,11 @@ private okhttp3.Call privateSetEmailForSubaccountGetValidateBeforeCall(Integer s * @param email The email address for the subaccount (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateSetEmailForSubaccountGet(Integer sid, String email) throws ApiException { ApiResponse localVarResp = privateSetEmailForSubaccountGetWithHttpInfo(sid, email); @@ -1052,6 +1274,11 @@ public Object privateSetEmailForSubaccountGet(Integer sid, String email) throws * @param email The email address for the subaccount (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateSetEmailForSubaccountGetWithHttpInfo(Integer sid, String email) throws ApiException { okhttp3.Call localVarCall = privateSetEmailForSubaccountGetValidateBeforeCall(sid, email, null); @@ -1067,6 +1294,11 @@ public ApiResponse privateSetEmailForSubaccountGetWithHttpInfo(Integer s * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateSetEmailForSubaccountGetAsync(Integer sid, String email, final ApiCallback _callback) throws ApiException { @@ -1081,6 +1313,11 @@ public okhttp3.Call privateSetEmailForSubaccountGetAsync(Integer sid, String ema * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateSetEmailLanguageGetCall(String language, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1134,6 +1371,11 @@ private okhttp3.Call privateSetEmailLanguageGetValidateBeforeCall(String languag * @param language The abbreviated language name. Valid values include `\"en\"`, `\"ko\"`, `\"zh\"` (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateSetEmailLanguageGet(String language) throws ApiException { ApiResponse localVarResp = privateSetEmailLanguageGetWithHttpInfo(language); @@ -1146,6 +1388,11 @@ public Object privateSetEmailLanguageGet(String language) throws ApiException { * @param language The abbreviated language name. Valid values include `\"en\"`, `\"ko\"`, `\"zh\"` (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateSetEmailLanguageGetWithHttpInfo(String language) throws ApiException { okhttp3.Call localVarCall = privateSetEmailLanguageGetValidateBeforeCall(language, null); @@ -1160,6 +1407,11 @@ public ApiResponse privateSetEmailLanguageGetWithHttpInfo(String languag * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateSetEmailLanguageGetAsync(String language, final ApiCallback _callback) throws ApiException { @@ -1175,6 +1427,11 @@ public okhttp3.Call privateSetEmailLanguageGetAsync(String language, final ApiCa * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateSetPasswordForSubaccountGetCall(Integer sid, String password, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1238,6 +1495,11 @@ private okhttp3.Call privateSetPasswordForSubaccountGetValidateBeforeCall(Intege * @param password The password for the subaccount (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateSetPasswordForSubaccountGet(Integer sid, String password) throws ApiException { ApiResponse localVarResp = privateSetPasswordForSubaccountGetWithHttpInfo(sid, password); @@ -1251,6 +1513,11 @@ public Object privateSetPasswordForSubaccountGet(Integer sid, String password) t * @param password The password for the subaccount (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateSetPasswordForSubaccountGetWithHttpInfo(Integer sid, String password) throws ApiException { okhttp3.Call localVarCall = privateSetPasswordForSubaccountGetValidateBeforeCall(sid, password, null); @@ -1266,6 +1533,11 @@ public ApiResponse privateSetPasswordForSubaccountGetWithHttpInfo(Intege * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateSetPasswordForSubaccountGetAsync(Integer sid, String password, final ApiCallback _callback) throws ApiException { @@ -1281,6 +1553,11 @@ public okhttp3.Call privateSetPasswordForSubaccountGetAsync(Integer sid, String * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateToggleNotificationsFromSubaccountGetCall(Integer sid, Boolean state, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1344,6 +1621,11 @@ private okhttp3.Call privateToggleNotificationsFromSubaccountGetValidateBeforeCa * @param state enable (`true`) or disable (`false`) notifications (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateToggleNotificationsFromSubaccountGet(Integer sid, Boolean state) throws ApiException { ApiResponse localVarResp = privateToggleNotificationsFromSubaccountGetWithHttpInfo(sid, state); @@ -1357,6 +1639,11 @@ public Object privateToggleNotificationsFromSubaccountGet(Integer sid, Boolean s * @param state enable (`true`) or disable (`false`) notifications (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateToggleNotificationsFromSubaccountGetWithHttpInfo(Integer sid, Boolean state) throws ApiException { okhttp3.Call localVarCall = privateToggleNotificationsFromSubaccountGetValidateBeforeCall(sid, state, null); @@ -1372,6 +1659,11 @@ public ApiResponse privateToggleNotificationsFromSubaccountGetWithHttpIn * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateToggleNotificationsFromSubaccountGetAsync(Integer sid, Boolean state, final ApiCallback _callback) throws ApiException { @@ -1387,6 +1679,11 @@ public okhttp3.Call privateToggleNotificationsFromSubaccountGetAsync(Integer sid * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateToggleSubaccountLoginGetCall(Integer sid, String state, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1450,6 +1747,11 @@ private okhttp3.Call privateToggleSubaccountLoginGetValidateBeforeCall(Integer s * @param state enable or disable login. (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateToggleSubaccountLoginGet(Integer sid, String state) throws ApiException { ApiResponse localVarResp = privateToggleSubaccountLoginGetWithHttpInfo(sid, state); @@ -1463,6 +1765,11 @@ public Object privateToggleSubaccountLoginGet(Integer sid, String state) throws * @param state enable or disable login. (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateToggleSubaccountLoginGetWithHttpInfo(Integer sid, String state) throws ApiException { okhttp3.Call localVarCall = privateToggleSubaccountLoginGetValidateBeforeCall(sid, state, null); @@ -1478,6 +1785,11 @@ public ApiResponse privateToggleSubaccountLoginGetWithHttpInfo(Integer s * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateToggleSubaccountLoginGetAsync(Integer sid, String state, final ApiCallback _callback) throws ApiException { @@ -1491,6 +1803,11 @@ public okhttp3.Call privateToggleSubaccountLoginGetAsync(Integer sid, String sta * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetAnnouncementsGetCall(final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1534,6 +1851,11 @@ private okhttp3.Call publicGetAnnouncementsGetValidateBeforeCall(final ApiCallba * * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetAnnouncementsGet() throws ApiException { ApiResponse localVarResp = publicGetAnnouncementsGetWithHttpInfo(); @@ -1545,6 +1867,11 @@ public Object publicGetAnnouncementsGet() throws ApiException { * * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetAnnouncementsGetWithHttpInfo() throws ApiException { okhttp3.Call localVarCall = publicGetAnnouncementsGetValidateBeforeCall(null); @@ -1558,6 +1885,11 @@ public ApiResponse publicGetAnnouncementsGetWithHttpInfo() throws ApiExc * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetAnnouncementsGetAsync(final ApiCallback _callback) throws ApiException { diff --git a/java/src/main/java/org/openapitools/client/api/AuthenticationApi.java b/java/src/main/java/org/openapitools/client/api/AuthenticationApi.java index 5dadd5e..a2bf898 100644 --- a/java/src/main/java/org/openapitools/client/api/AuthenticationApi.java +++ b/java/src/main/java/org/openapitools/client/api/AuthenticationApi.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -69,6 +69,12 @@ public void setApiClient(ApiClient apiClient) { * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + +
Status Code Description Response Headers
200 ok response -
429 over limit -
*/ public okhttp3.Call publicAuthGetCall(String grantType, String username, String password, String clientId, String clientSecret, String refreshToken, String timestamp, String signature, String nonce, String state, String scope, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -207,6 +213,12 @@ private okhttp3.Call publicAuthGetValidateBeforeCall(String grantType, String us * @param scope Describes type of the access for assigned token, possible values: `connection`, `session`, `session:name`, `trade:[read, read_write, none]`, `wallet:[read, read_write, none]`, `account:[read, read_write, none]`, `expires:NUMBER` (token will expire after `NUMBER` of seconds).</BR></BR> **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read``` (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
Status Code Description Response Headers
200 ok response -
429 over limit -
*/ public Object publicAuthGet(String grantType, String username, String password, String clientId, String clientSecret, String refreshToken, String timestamp, String signature, String nonce, String state, String scope) throws ApiException { ApiResponse localVarResp = publicAuthGetWithHttpInfo(grantType, username, password, clientId, clientSecret, refreshToken, timestamp, signature, nonce, state, scope); @@ -229,6 +241,12 @@ public Object publicAuthGet(String grantType, String username, String password, * @param scope Describes type of the access for assigned token, possible values: `connection`, `session`, `session:name`, `trade:[read, read_write, none]`, `wallet:[read, read_write, none]`, `account:[read, read_write, none]`, `expires:NUMBER` (token will expire after `NUMBER` of seconds).</BR></BR> **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read``` (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
Status Code Description Response Headers
200 ok response -
429 over limit -
*/ public ApiResponse publicAuthGetWithHttpInfo(String grantType, String username, String password, String clientId, String clientSecret, String refreshToken, String timestamp, String signature, String nonce, String state, String scope) throws ApiException { okhttp3.Call localVarCall = publicAuthGetValidateBeforeCall(grantType, username, password, clientId, clientSecret, refreshToken, timestamp, signature, nonce, state, scope, null); @@ -253,6 +271,12 @@ public ApiResponse publicAuthGetWithHttpInfo(String grantType, String us * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + +
Status Code Description Response Headers
200 ok response -
429 over limit -
*/ public okhttp3.Call publicAuthGetAsync(String grantType, String username, String password, String clientId, String clientSecret, String refreshToken, String timestamp, String signature, String nonce, String state, String scope, final ApiCallback _callback) throws ApiException { diff --git a/java/src/main/java/org/openapitools/client/api/InternalApi.java b/java/src/main/java/org/openapitools/client/api/InternalApi.java index 08fcd75..afdab88 100644 --- a/java/src/main/java/org/openapitools/client/api/InternalApi.java +++ b/java/src/main/java/org/openapitools/client/api/InternalApi.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -64,6 +64,11 @@ public void setApiClient(ApiClient apiClient) { * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateAddToAddressBookGetCall(String currency, String type, String address, String name, String tfa, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -152,6 +157,11 @@ private okhttp3.Call privateAddToAddressBookGetValidateBeforeCall(String currenc * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateAddToAddressBookGet(String currency, String type, String address, String name, String tfa) throws ApiException { ApiResponse localVarResp = privateAddToAddressBookGetWithHttpInfo(currency, type, address, name, tfa); @@ -168,6 +178,11 @@ public Object privateAddToAddressBookGet(String currency, String type, String ad * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateAddToAddressBookGetWithHttpInfo(String currency, String type, String address, String name, String tfa) throws ApiException { okhttp3.Call localVarCall = privateAddToAddressBookGetValidateBeforeCall(currency, type, address, name, tfa, null); @@ -186,6 +201,11 @@ public ApiResponse privateAddToAddressBookGetWithHttpInfo(String currenc * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateAddToAddressBookGetAsync(String currency, String type, String address, String name, String tfa, final ApiCallback _callback) throws ApiException { @@ -201,6 +221,11 @@ public okhttp3.Call privateAddToAddressBookGetAsync(String currency, String type * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateDisableTfaWithRecoveryCodeGetCall(String password, String code, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -264,6 +289,11 @@ private okhttp3.Call privateDisableTfaWithRecoveryCodeGetValidateBeforeCall(Stri * @param code One time recovery code (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateDisableTfaWithRecoveryCodeGet(String password, String code) throws ApiException { ApiResponse localVarResp = privateDisableTfaWithRecoveryCodeGetWithHttpInfo(password, code); @@ -277,6 +307,11 @@ public Object privateDisableTfaWithRecoveryCodeGet(String password, String code) * @param code One time recovery code (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateDisableTfaWithRecoveryCodeGetWithHttpInfo(String password, String code) throws ApiException { okhttp3.Call localVarCall = privateDisableTfaWithRecoveryCodeGetValidateBeforeCall(password, code, null); @@ -292,6 +327,11 @@ public ApiResponse privateDisableTfaWithRecoveryCodeGetWithHttpInfo(Stri * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateDisableTfaWithRecoveryCodeGetAsync(String password, String code, final ApiCallback _callback) throws ApiException { @@ -307,6 +347,11 @@ public okhttp3.Call privateDisableTfaWithRecoveryCodeGetAsync(String password, S * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetAddressBookGetCall(String currency, String type, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -370,6 +415,11 @@ private okhttp3.Call privateGetAddressBookGetValidateBeforeCall(String currency, * @param type Address book type (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetAddressBookGet(String currency, String type) throws ApiException { ApiResponse localVarResp = privateGetAddressBookGetWithHttpInfo(currency, type); @@ -383,6 +433,11 @@ public Object privateGetAddressBookGet(String currency, String type) throws ApiE * @param type Address book type (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetAddressBookGetWithHttpInfo(String currency, String type) throws ApiException { okhttp3.Call localVarCall = privateGetAddressBookGetValidateBeforeCall(currency, type, null); @@ -398,6 +453,11 @@ public ApiResponse privateGetAddressBookGetWithHttpInfo(String currency, * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetAddressBookGetAsync(String currency, String type, final ApiCallback _callback) throws ApiException { @@ -415,6 +475,11 @@ public okhttp3.Call privateGetAddressBookGetAsync(String currency, String type, * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateRemoveFromAddressBookGetCall(String currency, String type, String address, String tfa, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -493,6 +558,11 @@ private okhttp3.Call privateRemoveFromAddressBookGetValidateBeforeCall(String cu * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateRemoveFromAddressBookGet(String currency, String type, String address, String tfa) throws ApiException { ApiResponse localVarResp = privateRemoveFromAddressBookGetWithHttpInfo(currency, type, address, tfa); @@ -508,6 +578,11 @@ public Object privateRemoveFromAddressBookGet(String currency, String type, Stri * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateRemoveFromAddressBookGetWithHttpInfo(String currency, String type, String address, String tfa) throws ApiException { okhttp3.Call localVarCall = privateRemoveFromAddressBookGetValidateBeforeCall(currency, type, address, tfa, null); @@ -525,6 +600,11 @@ public ApiResponse privateRemoveFromAddressBookGetWithHttpInfo(String cu * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateRemoveFromAddressBookGetAsync(String currency, String type, String address, String tfa, final ApiCallback _callback) throws ApiException { @@ -541,6 +621,11 @@ public okhttp3.Call privateRemoveFromAddressBookGetAsync(String currency, String * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateSubmitTransferToSubaccountGetCall(String currency, BigDecimal amount, Integer destination, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -614,6 +699,11 @@ private okhttp3.Call privateSubmitTransferToSubaccountGetValidateBeforeCall(Stri * @param destination Id of destination subaccount (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateSubmitTransferToSubaccountGet(String currency, BigDecimal amount, Integer destination) throws ApiException { ApiResponse localVarResp = privateSubmitTransferToSubaccountGetWithHttpInfo(currency, amount, destination); @@ -628,6 +718,11 @@ public Object privateSubmitTransferToSubaccountGet(String currency, BigDecimal a * @param destination Id of destination subaccount (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateSubmitTransferToSubaccountGetWithHttpInfo(String currency, BigDecimal amount, Integer destination) throws ApiException { okhttp3.Call localVarCall = privateSubmitTransferToSubaccountGetValidateBeforeCall(currency, amount, destination, null); @@ -644,6 +739,11 @@ public ApiResponse privateSubmitTransferToSubaccountGetWithHttpInfo(Stri * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateSubmitTransferToSubaccountGetAsync(String currency, BigDecimal amount, Integer destination, final ApiCallback _callback) throws ApiException { @@ -661,6 +761,11 @@ public okhttp3.Call privateSubmitTransferToSubaccountGetAsync(String currency, B * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateSubmitTransferToUserGetCall(String currency, BigDecimal amount, String destination, String tfa, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -739,6 +844,11 @@ private okhttp3.Call privateSubmitTransferToUserGetValidateBeforeCall(String cur * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateSubmitTransferToUserGet(String currency, BigDecimal amount, String destination, String tfa) throws ApiException { ApiResponse localVarResp = privateSubmitTransferToUserGetWithHttpInfo(currency, amount, destination, tfa); @@ -754,6 +864,11 @@ public Object privateSubmitTransferToUserGet(String currency, BigDecimal amount, * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateSubmitTransferToUserGetWithHttpInfo(String currency, BigDecimal amount, String destination, String tfa) throws ApiException { okhttp3.Call localVarCall = privateSubmitTransferToUserGetValidateBeforeCall(currency, amount, destination, tfa, null); @@ -771,6 +886,11 @@ public ApiResponse privateSubmitTransferToUserGetWithHttpInfo(String cur * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateSubmitTransferToUserGetAsync(String currency, BigDecimal amount, String destination, String tfa, final ApiCallback _callback) throws ApiException { @@ -786,6 +906,11 @@ public okhttp3.Call privateSubmitTransferToUserGetAsync(String currency, BigDeci * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateToggleDepositAddressCreationGetCall(String currency, Boolean state, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -849,6 +974,11 @@ private okhttp3.Call privateToggleDepositAddressCreationGetValidateBeforeCall(St * @param state (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateToggleDepositAddressCreationGet(String currency, Boolean state) throws ApiException { ApiResponse localVarResp = privateToggleDepositAddressCreationGetWithHttpInfo(currency, state); @@ -862,6 +992,11 @@ public Object privateToggleDepositAddressCreationGet(String currency, Boolean st * @param state (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateToggleDepositAddressCreationGetWithHttpInfo(String currency, Boolean state) throws ApiException { okhttp3.Call localVarCall = privateToggleDepositAddressCreationGetValidateBeforeCall(currency, state, null); @@ -877,6 +1012,11 @@ public ApiResponse privateToggleDepositAddressCreationGetWithHttpInfo(St * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateToggleDepositAddressCreationGetAsync(String currency, Boolean state, final ApiCallback _callback) throws ApiException { @@ -890,6 +1030,11 @@ public okhttp3.Call privateToggleDepositAddressCreationGetAsync(String currency, * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call publicGetFooterGetCall(final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -933,6 +1078,11 @@ private okhttp3.Call publicGetFooterGetValidateBeforeCall(final ApiCallback _cal * * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object publicGetFooterGet() throws ApiException { ApiResponse localVarResp = publicGetFooterGetWithHttpInfo(); @@ -944,6 +1094,11 @@ public Object publicGetFooterGet() throws ApiException { * * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse publicGetFooterGetWithHttpInfo() throws ApiException { okhttp3.Call localVarCall = publicGetFooterGetValidateBeforeCall(null); @@ -957,6 +1112,11 @@ public ApiResponse publicGetFooterGetWithHttpInfo() throws ApiException * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call publicGetFooterGetAsync(final ApiCallback _callback) throws ApiException { @@ -971,6 +1131,11 @@ public okhttp3.Call publicGetFooterGetAsync(final ApiCallback _callback) * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call publicGetOptionMarkPricesGetCall(String currency, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1024,6 +1189,11 @@ private okhttp3.Call publicGetOptionMarkPricesGetValidateBeforeCall(String curre * @param currency The currency symbol (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object publicGetOptionMarkPricesGet(String currency) throws ApiException { ApiResponse localVarResp = publicGetOptionMarkPricesGetWithHttpInfo(currency); @@ -1036,6 +1206,11 @@ public Object publicGetOptionMarkPricesGet(String currency) throws ApiException * @param currency The currency symbol (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse publicGetOptionMarkPricesGetWithHttpInfo(String currency) throws ApiException { okhttp3.Call localVarCall = publicGetOptionMarkPricesGetValidateBeforeCall(currency, null); @@ -1050,6 +1225,11 @@ public ApiResponse publicGetOptionMarkPricesGetWithHttpInfo(String curre * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call publicGetOptionMarkPricesGetAsync(String currency, final ApiCallback _callback) throws ApiException { @@ -1066,6 +1246,11 @@ public okhttp3.Call publicGetOptionMarkPricesGetAsync(String currency, final Api * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicValidateFieldGetCall(String field, String value, String value2, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1134,6 +1319,11 @@ private okhttp3.Call publicValidateFieldGetValidateBeforeCall(String field, Stri * @param value2 Additional value to be compared with (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicValidateFieldGet(String field, String value, String value2) throws ApiException { ApiResponse localVarResp = publicValidateFieldGetWithHttpInfo(field, value, value2); @@ -1148,6 +1338,11 @@ public Object publicValidateFieldGet(String field, String value, String value2) * @param value2 Additional value to be compared with (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicValidateFieldGetWithHttpInfo(String field, String value, String value2) throws ApiException { okhttp3.Call localVarCall = publicValidateFieldGetValidateBeforeCall(field, value, value2, null); @@ -1164,6 +1359,11 @@ public ApiResponse publicValidateFieldGetWithHttpInfo(String field, Stri * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicValidateFieldGetAsync(String field, String value, String value2, final ApiCallback _callback) throws ApiException { diff --git a/java/src/main/java/org/openapitools/client/api/MarketDataApi.java b/java/src/main/java/org/openapitools/client/api/MarketDataApi.java index bc6d008..e9bc979 100644 --- a/java/src/main/java/org/openapitools/client/api/MarketDataApi.java +++ b/java/src/main/java/org/openapitools/client/api/MarketDataApi.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -61,6 +61,11 @@ public void setApiClient(ApiClient apiClient) { * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetBookSummaryByCurrencyGetCall(String currency, String kind, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -119,6 +124,11 @@ private okhttp3.Call publicGetBookSummaryByCurrencyGetValidateBeforeCall(String * @param kind Instrument kind, if not provided instruments of all kinds are considered (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetBookSummaryByCurrencyGet(String currency, String kind) throws ApiException { ApiResponse localVarResp = publicGetBookSummaryByCurrencyGetWithHttpInfo(currency, kind); @@ -132,6 +142,11 @@ public Object publicGetBookSummaryByCurrencyGet(String currency, String kind) th * @param kind Instrument kind, if not provided instruments of all kinds are considered (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetBookSummaryByCurrencyGetWithHttpInfo(String currency, String kind) throws ApiException { okhttp3.Call localVarCall = publicGetBookSummaryByCurrencyGetValidateBeforeCall(currency, kind, null); @@ -147,6 +162,11 @@ public ApiResponse publicGetBookSummaryByCurrencyGetWithHttpInfo(String * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetBookSummaryByCurrencyGetAsync(String currency, String kind, final ApiCallback _callback) throws ApiException { @@ -161,6 +181,11 @@ public okhttp3.Call publicGetBookSummaryByCurrencyGetAsync(String currency, Stri * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetBookSummaryByInstrumentGetCall(String instrumentName, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -214,6 +239,11 @@ private okhttp3.Call publicGetBookSummaryByInstrumentGetValidateBeforeCall(Strin * @param instrumentName Instrument name (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetBookSummaryByInstrumentGet(String instrumentName) throws ApiException { ApiResponse localVarResp = publicGetBookSummaryByInstrumentGetWithHttpInfo(instrumentName); @@ -226,6 +256,11 @@ public Object publicGetBookSummaryByInstrumentGet(String instrumentName) throws * @param instrumentName Instrument name (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetBookSummaryByInstrumentGetWithHttpInfo(String instrumentName) throws ApiException { okhttp3.Call localVarCall = publicGetBookSummaryByInstrumentGetValidateBeforeCall(instrumentName, null); @@ -240,6 +275,11 @@ public ApiResponse publicGetBookSummaryByInstrumentGetWithHttpInfo(Strin * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetBookSummaryByInstrumentGetAsync(String instrumentName, final ApiCallback _callback) throws ApiException { @@ -254,6 +294,11 @@ public okhttp3.Call publicGetBookSummaryByInstrumentGetAsync(String instrumentNa * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call publicGetContractSizeGetCall(String instrumentName, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -307,6 +352,11 @@ private okhttp3.Call publicGetContractSizeGetValidateBeforeCall(String instrumen * @param instrumentName Instrument name (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object publicGetContractSizeGet(String instrumentName) throws ApiException { ApiResponse localVarResp = publicGetContractSizeGetWithHttpInfo(instrumentName); @@ -319,6 +369,11 @@ public Object publicGetContractSizeGet(String instrumentName) throws ApiExceptio * @param instrumentName Instrument name (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse publicGetContractSizeGetWithHttpInfo(String instrumentName) throws ApiException { okhttp3.Call localVarCall = publicGetContractSizeGetValidateBeforeCall(instrumentName, null); @@ -333,6 +388,11 @@ public ApiResponse publicGetContractSizeGetWithHttpInfo(String instrumen * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call publicGetContractSizeGetAsync(String instrumentName, final ApiCallback _callback) throws ApiException { @@ -346,6 +406,11 @@ public okhttp3.Call publicGetContractSizeGetAsync(String instrumentName, final A * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call publicGetCurrenciesGetCall(final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -389,6 +454,11 @@ private okhttp3.Call publicGetCurrenciesGetValidateBeforeCall(final ApiCallback * * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object publicGetCurrenciesGet() throws ApiException { ApiResponse localVarResp = publicGetCurrenciesGetWithHttpInfo(); @@ -400,6 +470,11 @@ public Object publicGetCurrenciesGet() throws ApiException { * * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse publicGetCurrenciesGetWithHttpInfo() throws ApiException { okhttp3.Call localVarCall = publicGetCurrenciesGetValidateBeforeCall(null); @@ -413,6 +488,11 @@ public ApiResponse publicGetCurrenciesGetWithHttpInfo() throws ApiExcept * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call publicGetCurrenciesGetAsync(final ApiCallback _callback) throws ApiException { @@ -428,6 +508,11 @@ public okhttp3.Call publicGetCurrenciesGetAsync(final ApiCallback _callb * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetFundingChartDataGetCall(String instrumentName, String length, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -486,6 +571,11 @@ private okhttp3.Call publicGetFundingChartDataGetValidateBeforeCall(String instr * @param length Specifies time period. `8h` - 8 hours, `24h` - 24 hours (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetFundingChartDataGet(String instrumentName, String length) throws ApiException { ApiResponse localVarResp = publicGetFundingChartDataGetWithHttpInfo(instrumentName, length); @@ -499,6 +589,11 @@ public Object publicGetFundingChartDataGet(String instrumentName, String length) * @param length Specifies time period. `8h` - 8 hours, `24h` - 24 hours (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetFundingChartDataGetWithHttpInfo(String instrumentName, String length) throws ApiException { okhttp3.Call localVarCall = publicGetFundingChartDataGetValidateBeforeCall(instrumentName, length, null); @@ -514,6 +609,11 @@ public ApiResponse publicGetFundingChartDataGetWithHttpInfo(String instr * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetFundingChartDataGetAsync(String instrumentName, String length, final ApiCallback _callback) throws ApiException { @@ -528,6 +628,11 @@ public okhttp3.Call publicGetFundingChartDataGetAsync(String instrumentName, Str * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call publicGetHistoricalVolatilityGetCall(String currency, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -581,6 +686,11 @@ private okhttp3.Call publicGetHistoricalVolatilityGetValidateBeforeCall(String c * @param currency The currency symbol (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object publicGetHistoricalVolatilityGet(String currency) throws ApiException { ApiResponse localVarResp = publicGetHistoricalVolatilityGetWithHttpInfo(currency); @@ -593,6 +703,11 @@ public Object publicGetHistoricalVolatilityGet(String currency) throws ApiExcept * @param currency The currency symbol (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse publicGetHistoricalVolatilityGetWithHttpInfo(String currency) throws ApiException { okhttp3.Call localVarCall = publicGetHistoricalVolatilityGetValidateBeforeCall(currency, null); @@ -607,6 +722,11 @@ public ApiResponse publicGetHistoricalVolatilityGetWithHttpInfo(String c * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call publicGetHistoricalVolatilityGetAsync(String currency, final ApiCallback _callback) throws ApiException { @@ -621,6 +741,11 @@ public okhttp3.Call publicGetHistoricalVolatilityGetAsync(String currency, final * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetIndexGetCall(String currency, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -674,6 +799,11 @@ private okhttp3.Call publicGetIndexGetValidateBeforeCall(String currency, final * @param currency The currency symbol (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetIndexGet(String currency) throws ApiException { ApiResponse localVarResp = publicGetIndexGetWithHttpInfo(currency); @@ -686,6 +816,11 @@ public Object publicGetIndexGet(String currency) throws ApiException { * @param currency The currency symbol (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetIndexGetWithHttpInfo(String currency) throws ApiException { okhttp3.Call localVarCall = publicGetIndexGetValidateBeforeCall(currency, null); @@ -700,6 +835,11 @@ public ApiResponse publicGetIndexGetWithHttpInfo(String currency) throws * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetIndexGetAsync(String currency, final ApiCallback _callback) throws ApiException { @@ -716,6 +856,11 @@ public okhttp3.Call publicGetIndexGetAsync(String currency, final ApiCallback + Status Code Description Response Headers + 200 ok response - + */ public okhttp3.Call publicGetInstrumentsGetCall(String currency, String kind, Boolean expired, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -779,6 +924,11 @@ private okhttp3.Call publicGetInstrumentsGetValidateBeforeCall(String currency, * @param expired Set to true to show expired instruments instead of active ones. (optional, default to false) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object publicGetInstrumentsGet(String currency, String kind, Boolean expired) throws ApiException { ApiResponse localVarResp = publicGetInstrumentsGetWithHttpInfo(currency, kind, expired); @@ -793,6 +943,11 @@ public Object publicGetInstrumentsGet(String currency, String kind, Boolean expi * @param expired Set to true to show expired instruments instead of active ones. (optional, default to false) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse publicGetInstrumentsGetWithHttpInfo(String currency, String kind, Boolean expired) throws ApiException { okhttp3.Call localVarCall = publicGetInstrumentsGetValidateBeforeCall(currency, kind, expired, null); @@ -809,6 +964,11 @@ public ApiResponse publicGetInstrumentsGetWithHttpInfo(String currency, * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call publicGetInstrumentsGetAsync(String currency, String kind, Boolean expired, final ApiCallback _callback) throws ApiException { @@ -827,6 +987,11 @@ public okhttp3.Call publicGetInstrumentsGetAsync(String currency, String kind, B * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetLastSettlementsByCurrencyGetCall(String currency, String type, Integer count, String continuation, Integer searchStartTimestamp, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -900,6 +1065,11 @@ private okhttp3.Call publicGetLastSettlementsByCurrencyGetValidateBeforeCall(Str * @param searchStartTimestamp The latest timestamp to return result for (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetLastSettlementsByCurrencyGet(String currency, String type, Integer count, String continuation, Integer searchStartTimestamp) throws ApiException { ApiResponse localVarResp = publicGetLastSettlementsByCurrencyGetWithHttpInfo(currency, type, count, continuation, searchStartTimestamp); @@ -916,6 +1086,11 @@ public Object publicGetLastSettlementsByCurrencyGet(String currency, String type * @param searchStartTimestamp The latest timestamp to return result for (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetLastSettlementsByCurrencyGetWithHttpInfo(String currency, String type, Integer count, String continuation, Integer searchStartTimestamp) throws ApiException { okhttp3.Call localVarCall = publicGetLastSettlementsByCurrencyGetValidateBeforeCall(currency, type, count, continuation, searchStartTimestamp, null); @@ -934,6 +1109,11 @@ public ApiResponse publicGetLastSettlementsByCurrencyGetWithHttpInfo(Str * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetLastSettlementsByCurrencyGetAsync(String currency, String type, Integer count, String continuation, Integer searchStartTimestamp, final ApiCallback _callback) throws ApiException { @@ -952,6 +1132,11 @@ public okhttp3.Call publicGetLastSettlementsByCurrencyGetAsync(String currency, * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetLastSettlementsByInstrumentGetCall(String instrumentName, String type, Integer count, String continuation, Integer searchStartTimestamp, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1025,6 +1210,11 @@ private okhttp3.Call publicGetLastSettlementsByInstrumentGetValidateBeforeCall(S * @param searchStartTimestamp The latest timestamp to return result for (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetLastSettlementsByInstrumentGet(String instrumentName, String type, Integer count, String continuation, Integer searchStartTimestamp) throws ApiException { ApiResponse localVarResp = publicGetLastSettlementsByInstrumentGetWithHttpInfo(instrumentName, type, count, continuation, searchStartTimestamp); @@ -1041,6 +1231,11 @@ public Object publicGetLastSettlementsByInstrumentGet(String instrumentName, Str * @param searchStartTimestamp The latest timestamp to return result for (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetLastSettlementsByInstrumentGetWithHttpInfo(String instrumentName, String type, Integer count, String continuation, Integer searchStartTimestamp) throws ApiException { okhttp3.Call localVarCall = publicGetLastSettlementsByInstrumentGetValidateBeforeCall(instrumentName, type, count, continuation, searchStartTimestamp, null); @@ -1059,6 +1254,11 @@ public ApiResponse publicGetLastSettlementsByInstrumentGetWithHttpInfo(S * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetLastSettlementsByInstrumentGetAsync(String instrumentName, String type, Integer count, String continuation, Integer searchStartTimestamp, final ApiCallback _callback) throws ApiException { @@ -1079,6 +1279,11 @@ public okhttp3.Call publicGetLastSettlementsByInstrumentGetAsync(String instrume * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetLastTradesByCurrencyAndTimeGetCall(String currency, Integer startTimestamp, Integer endTimestamp, String kind, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1172,6 +1377,11 @@ private okhttp3.Call publicGetLastTradesByCurrencyAndTimeGetValidateBeforeCall(S * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetLastTradesByCurrencyAndTimeGet(String currency, Integer startTimestamp, Integer endTimestamp, String kind, Integer count, Boolean includeOld, String sorting) throws ApiException { ApiResponse localVarResp = publicGetLastTradesByCurrencyAndTimeGetWithHttpInfo(currency, startTimestamp, endTimestamp, kind, count, includeOld, sorting); @@ -1190,6 +1400,11 @@ public Object publicGetLastTradesByCurrencyAndTimeGet(String currency, Integer s * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetLastTradesByCurrencyAndTimeGetWithHttpInfo(String currency, Integer startTimestamp, Integer endTimestamp, String kind, Integer count, Boolean includeOld, String sorting) throws ApiException { okhttp3.Call localVarCall = publicGetLastTradesByCurrencyAndTimeGetValidateBeforeCall(currency, startTimestamp, endTimestamp, kind, count, includeOld, sorting, null); @@ -1210,6 +1425,11 @@ public ApiResponse publicGetLastTradesByCurrencyAndTimeGetWithHttpInfo(S * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetLastTradesByCurrencyAndTimeGetAsync(String currency, Integer startTimestamp, Integer endTimestamp, String kind, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { @@ -1230,6 +1450,11 @@ public okhttp3.Call publicGetLastTradesByCurrencyAndTimeGetAsync(String currency * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetLastTradesByCurrencyGetCall(String currency, String kind, String startId, String endId, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1313,6 +1538,11 @@ private okhttp3.Call publicGetLastTradesByCurrencyGetValidateBeforeCall(String c * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetLastTradesByCurrencyGet(String currency, String kind, String startId, String endId, Integer count, Boolean includeOld, String sorting) throws ApiException { ApiResponse localVarResp = publicGetLastTradesByCurrencyGetWithHttpInfo(currency, kind, startId, endId, count, includeOld, sorting); @@ -1331,6 +1561,11 @@ public Object publicGetLastTradesByCurrencyGet(String currency, String kind, Str * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetLastTradesByCurrencyGetWithHttpInfo(String currency, String kind, String startId, String endId, Integer count, Boolean includeOld, String sorting) throws ApiException { okhttp3.Call localVarCall = publicGetLastTradesByCurrencyGetValidateBeforeCall(currency, kind, startId, endId, count, includeOld, sorting, null); @@ -1351,6 +1586,11 @@ public ApiResponse publicGetLastTradesByCurrencyGetWithHttpInfo(String c * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetLastTradesByCurrencyGetAsync(String currency, String kind, String startId, String endId, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { @@ -1370,6 +1610,11 @@ public okhttp3.Call publicGetLastTradesByCurrencyGetAsync(String currency, Strin * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetLastTradesByInstrumentAndTimeGetCall(String instrumentName, Integer startTimestamp, Integer endTimestamp, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1458,6 +1703,11 @@ private okhttp3.Call publicGetLastTradesByInstrumentAndTimeGetValidateBeforeCall * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetLastTradesByInstrumentAndTimeGet(String instrumentName, Integer startTimestamp, Integer endTimestamp, Integer count, Boolean includeOld, String sorting) throws ApiException { ApiResponse localVarResp = publicGetLastTradesByInstrumentAndTimeGetWithHttpInfo(instrumentName, startTimestamp, endTimestamp, count, includeOld, sorting); @@ -1475,6 +1725,11 @@ public Object publicGetLastTradesByInstrumentAndTimeGet(String instrumentName, I * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetLastTradesByInstrumentAndTimeGetWithHttpInfo(String instrumentName, Integer startTimestamp, Integer endTimestamp, Integer count, Boolean includeOld, String sorting) throws ApiException { okhttp3.Call localVarCall = publicGetLastTradesByInstrumentAndTimeGetValidateBeforeCall(instrumentName, startTimestamp, endTimestamp, count, includeOld, sorting, null); @@ -1494,6 +1749,11 @@ public ApiResponse publicGetLastTradesByInstrumentAndTimeGetWithHttpInfo * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetLastTradesByInstrumentAndTimeGetAsync(String instrumentName, Integer startTimestamp, Integer endTimestamp, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { @@ -1513,6 +1773,11 @@ public okhttp3.Call publicGetLastTradesByInstrumentAndTimeGetAsync(String instru * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetLastTradesByInstrumentGetCall(String instrumentName, Integer startSeq, Integer endSeq, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1591,6 +1856,11 @@ private okhttp3.Call publicGetLastTradesByInstrumentGetValidateBeforeCall(String * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetLastTradesByInstrumentGet(String instrumentName, Integer startSeq, Integer endSeq, Integer count, Boolean includeOld, String sorting) throws ApiException { ApiResponse localVarResp = publicGetLastTradesByInstrumentGetWithHttpInfo(instrumentName, startSeq, endSeq, count, includeOld, sorting); @@ -1608,6 +1878,11 @@ public Object publicGetLastTradesByInstrumentGet(String instrumentName, Integer * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetLastTradesByInstrumentGetWithHttpInfo(String instrumentName, Integer startSeq, Integer endSeq, Integer count, Boolean includeOld, String sorting) throws ApiException { okhttp3.Call localVarCall = publicGetLastTradesByInstrumentGetValidateBeforeCall(instrumentName, startSeq, endSeq, count, includeOld, sorting, null); @@ -1627,6 +1902,11 @@ public ApiResponse publicGetLastTradesByInstrumentGetWithHttpInfo(String * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetLastTradesByInstrumentGetAsync(String instrumentName, Integer startSeq, Integer endSeq, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { @@ -1642,6 +1922,11 @@ public okhttp3.Call publicGetLastTradesByInstrumentGetAsync(String instrumentNam * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetOrderBookGetCall(String instrumentName, BigDecimal depth, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1700,6 +1985,11 @@ private okhttp3.Call publicGetOrderBookGetValidateBeforeCall(String instrumentNa * @param depth The number of entries to return for bids and asks. (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetOrderBookGet(String instrumentName, BigDecimal depth) throws ApiException { ApiResponse localVarResp = publicGetOrderBookGetWithHttpInfo(instrumentName, depth); @@ -1713,6 +2003,11 @@ public Object publicGetOrderBookGet(String instrumentName, BigDecimal depth) thr * @param depth The number of entries to return for bids and asks. (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetOrderBookGetWithHttpInfo(String instrumentName, BigDecimal depth) throws ApiException { okhttp3.Call localVarCall = publicGetOrderBookGetValidateBeforeCall(instrumentName, depth, null); @@ -1728,6 +2023,11 @@ public ApiResponse publicGetOrderBookGetWithHttpInfo(String instrumentNa * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetOrderBookGetAsync(String instrumentName, BigDecimal depth, final ApiCallback _callback) throws ApiException { @@ -1741,6 +2041,11 @@ public okhttp3.Call publicGetOrderBookGetAsync(String instrumentName, BigDecimal * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetTradeVolumesGetCall(final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1784,6 +2089,11 @@ private okhttp3.Call publicGetTradeVolumesGetValidateBeforeCall(final ApiCallbac * * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetTradeVolumesGet() throws ApiException { ApiResponse localVarResp = publicGetTradeVolumesGetWithHttpInfo(); @@ -1795,6 +2105,11 @@ public Object publicGetTradeVolumesGet() throws ApiException { * * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetTradeVolumesGetWithHttpInfo() throws ApiException { okhttp3.Call localVarCall = publicGetTradeVolumesGetValidateBeforeCall(null); @@ -1808,6 +2123,11 @@ public ApiResponse publicGetTradeVolumesGetWithHttpInfo() throws ApiExce * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetTradeVolumesGetAsync(final ApiCallback _callback) throws ApiException { @@ -1824,6 +2144,11 @@ public okhttp3.Call publicGetTradeVolumesGetAsync(final ApiCallback _cal * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetTradingviewChartDataGetCall(String instrumentName, Integer startTimestamp, Integer endTimestamp, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1897,6 +2222,11 @@ private okhttp3.Call publicGetTradingviewChartDataGetValidateBeforeCall(String i * @param endTimestamp The most recent timestamp to return result for (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetTradingviewChartDataGet(String instrumentName, Integer startTimestamp, Integer endTimestamp) throws ApiException { ApiResponse localVarResp = publicGetTradingviewChartDataGetWithHttpInfo(instrumentName, startTimestamp, endTimestamp); @@ -1911,6 +2241,11 @@ public Object publicGetTradingviewChartDataGet(String instrumentName, Integer st * @param endTimestamp The most recent timestamp to return result for (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetTradingviewChartDataGetWithHttpInfo(String instrumentName, Integer startTimestamp, Integer endTimestamp) throws ApiException { okhttp3.Call localVarCall = publicGetTradingviewChartDataGetValidateBeforeCall(instrumentName, startTimestamp, endTimestamp, null); @@ -1927,6 +2262,11 @@ public ApiResponse publicGetTradingviewChartDataGetWithHttpInfo(String i * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetTradingviewChartDataGetAsync(String instrumentName, Integer startTimestamp, Integer endTimestamp, final ApiCallback _callback) throws ApiException { @@ -1941,6 +2281,11 @@ public okhttp3.Call publicGetTradingviewChartDataGetAsync(String instrumentName, * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call publicTickerGetCall(String instrumentName, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1994,6 +2339,11 @@ private okhttp3.Call publicTickerGetValidateBeforeCall(String instrumentName, fi * @param instrumentName Instrument name (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object publicTickerGet(String instrumentName) throws ApiException { ApiResponse localVarResp = publicTickerGetWithHttpInfo(instrumentName); @@ -2006,6 +2356,11 @@ public Object publicTickerGet(String instrumentName) throws ApiException { * @param instrumentName Instrument name (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse publicTickerGetWithHttpInfo(String instrumentName) throws ApiException { okhttp3.Call localVarCall = publicTickerGetValidateBeforeCall(instrumentName, null); @@ -2020,6 +2375,11 @@ public ApiResponse publicTickerGetWithHttpInfo(String instrumentName) th * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call publicTickerGetAsync(String instrumentName, final ApiCallback _callback) throws ApiException { diff --git a/java/src/main/java/org/openapitools/client/api/PrivateApi.java b/java/src/main/java/org/openapitools/client/api/PrivateApi.java index 33e0651..f9d9391 100644 --- a/java/src/main/java/org/openapitools/client/api/PrivateApi.java +++ b/java/src/main/java/org/openapitools/client/api/PrivateApi.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -64,6 +64,11 @@ public void setApiClient(ApiClient apiClient) { * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateAddToAddressBookGetCall(String currency, String type, String address, String name, String tfa, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -152,6 +157,11 @@ private okhttp3.Call privateAddToAddressBookGetValidateBeforeCall(String currenc * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateAddToAddressBookGet(String currency, String type, String address, String name, String tfa) throws ApiException { ApiResponse localVarResp = privateAddToAddressBookGetWithHttpInfo(currency, type, address, name, tfa); @@ -168,6 +178,11 @@ public Object privateAddToAddressBookGet(String currency, String type, String ad * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateAddToAddressBookGetWithHttpInfo(String currency, String type, String address, String name, String tfa) throws ApiException { okhttp3.Call localVarCall = privateAddToAddressBookGetValidateBeforeCall(currency, type, address, name, tfa, null); @@ -186,6 +201,11 @@ public ApiResponse privateAddToAddressBookGetWithHttpInfo(String currenc * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateAddToAddressBookGetAsync(String currency, String type, String address, String name, String tfa, final ApiCallback _callback) throws ApiException { @@ -211,6 +231,11 @@ public okhttp3.Call privateAddToAddressBookGetAsync(String currency, String type * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateBuyGetCall(String instrumentName, BigDecimal amount, String type, String label, BigDecimal price, String timeInForce, BigDecimal maxShow, Boolean postOnly, Boolean reduceOnly, BigDecimal stopPrice, String trigger, String advanced, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -324,6 +349,11 @@ private okhttp3.Call privateBuyGetValidateBeforeCall(String instrumentName, BigD * @param advanced Advanced option order type. (Only for options) (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateBuyGet(String instrumentName, BigDecimal amount, String type, String label, BigDecimal price, String timeInForce, BigDecimal maxShow, Boolean postOnly, Boolean reduceOnly, BigDecimal stopPrice, String trigger, String advanced) throws ApiException { ApiResponse localVarResp = privateBuyGetWithHttpInfo(instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced); @@ -347,6 +377,11 @@ public Object privateBuyGet(String instrumentName, BigDecimal amount, String typ * @param advanced Advanced option order type. (Only for options) (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateBuyGetWithHttpInfo(String instrumentName, BigDecimal amount, String type, String label, BigDecimal price, String timeInForce, BigDecimal maxShow, Boolean postOnly, Boolean reduceOnly, BigDecimal stopPrice, String trigger, String advanced) throws ApiException { okhttp3.Call localVarCall = privateBuyGetValidateBeforeCall(instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced, null); @@ -372,6 +407,11 @@ public ApiResponse privateBuyGetWithHttpInfo(String instrumentName, BigD * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateBuyGetAsync(String instrumentName, BigDecimal amount, String type, String label, BigDecimal price, String timeInForce, BigDecimal maxShow, Boolean postOnly, Boolean reduceOnly, BigDecimal stopPrice, String trigger, String advanced, final ApiCallback _callback) throws ApiException { @@ -388,6 +428,11 @@ public okhttp3.Call privateBuyGetAsync(String instrumentName, BigDecimal amount, * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateCancelAllByCurrencyGetCall(String currency, String kind, String type, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -451,6 +496,11 @@ private okhttp3.Call privateCancelAllByCurrencyGetValidateBeforeCall(String curr * @param type Order type - limit, stop or all, default - `all` (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateCancelAllByCurrencyGet(String currency, String kind, String type) throws ApiException { ApiResponse localVarResp = privateCancelAllByCurrencyGetWithHttpInfo(currency, kind, type); @@ -465,6 +515,11 @@ public Object privateCancelAllByCurrencyGet(String currency, String kind, String * @param type Order type - limit, stop or all, default - `all` (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateCancelAllByCurrencyGetWithHttpInfo(String currency, String kind, String type) throws ApiException { okhttp3.Call localVarCall = privateCancelAllByCurrencyGetValidateBeforeCall(currency, kind, type, null); @@ -481,6 +536,11 @@ public ApiResponse privateCancelAllByCurrencyGetWithHttpInfo(String curr * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateCancelAllByCurrencyGetAsync(String currency, String kind, String type, final ApiCallback _callback) throws ApiException { @@ -496,6 +556,11 @@ public okhttp3.Call privateCancelAllByCurrencyGetAsync(String currency, String k * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateCancelAllByInstrumentGetCall(String instrumentName, String type, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -554,6 +619,11 @@ private okhttp3.Call privateCancelAllByInstrumentGetValidateBeforeCall(String in * @param type Order type - limit, stop or all, default - `all` (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateCancelAllByInstrumentGet(String instrumentName, String type) throws ApiException { ApiResponse localVarResp = privateCancelAllByInstrumentGetWithHttpInfo(instrumentName, type); @@ -567,6 +637,11 @@ public Object privateCancelAllByInstrumentGet(String instrumentName, String type * @param type Order type - limit, stop or all, default - `all` (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateCancelAllByInstrumentGetWithHttpInfo(String instrumentName, String type) throws ApiException { okhttp3.Call localVarCall = privateCancelAllByInstrumentGetValidateBeforeCall(instrumentName, type, null); @@ -582,6 +657,11 @@ public ApiResponse privateCancelAllByInstrumentGetWithHttpInfo(String in * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateCancelAllByInstrumentGetAsync(String instrumentName, String type, final ApiCallback _callback) throws ApiException { @@ -595,6 +675,11 @@ public okhttp3.Call privateCancelAllByInstrumentGetAsync(String instrumentName, * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateCancelAllGetCall(final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -638,6 +723,11 @@ private okhttp3.Call privateCancelAllGetValidateBeforeCall(final ApiCallback _ca * * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateCancelAllGet() throws ApiException { ApiResponse localVarResp = privateCancelAllGetWithHttpInfo(); @@ -649,6 +739,11 @@ public Object privateCancelAllGet() throws ApiException { * * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateCancelAllGetWithHttpInfo() throws ApiException { okhttp3.Call localVarCall = privateCancelAllGetValidateBeforeCall(null); @@ -662,6 +757,11 @@ public ApiResponse privateCancelAllGetWithHttpInfo() throws ApiException * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateCancelAllGetAsync(final ApiCallback _callback) throws ApiException { @@ -676,6 +776,11 @@ public okhttp3.Call privateCancelAllGetAsync(final ApiCallback _callback * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateCancelGetCall(String orderId, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -729,6 +834,11 @@ private okhttp3.Call privateCancelGetValidateBeforeCall(String orderId, final Ap * @param orderId The order id (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateCancelGet(String orderId) throws ApiException { ApiResponse localVarResp = privateCancelGetWithHttpInfo(orderId); @@ -741,6 +851,11 @@ public Object privateCancelGet(String orderId) throws ApiException { * @param orderId The order id (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateCancelGetWithHttpInfo(String orderId) throws ApiException { okhttp3.Call localVarCall = privateCancelGetValidateBeforeCall(orderId, null); @@ -755,6 +870,11 @@ public ApiResponse privateCancelGetWithHttpInfo(String orderId) throws A * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateCancelGetAsync(String orderId, final ApiCallback _callback) throws ApiException { @@ -771,6 +891,11 @@ public okhttp3.Call privateCancelGetAsync(String orderId, final ApiCallback + Status Code Description Response Headers + 200 ok response - + */ public okhttp3.Call privateCancelTransferByIdGetCall(String currency, Integer id, String tfa, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -839,6 +964,11 @@ private okhttp3.Call privateCancelTransferByIdGetValidateBeforeCall(String curre * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateCancelTransferByIdGet(String currency, Integer id, String tfa) throws ApiException { ApiResponse localVarResp = privateCancelTransferByIdGetWithHttpInfo(currency, id, tfa); @@ -853,6 +983,11 @@ public Object privateCancelTransferByIdGet(String currency, Integer id, String t * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateCancelTransferByIdGetWithHttpInfo(String currency, Integer id, String tfa) throws ApiException { okhttp3.Call localVarCall = privateCancelTransferByIdGetValidateBeforeCall(currency, id, tfa, null); @@ -869,6 +1004,11 @@ public ApiResponse privateCancelTransferByIdGetWithHttpInfo(String curre * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateCancelTransferByIdGetAsync(String currency, Integer id, String tfa, final ApiCallback _callback) throws ApiException { @@ -884,6 +1024,11 @@ public okhttp3.Call privateCancelTransferByIdGetAsync(String currency, Integer i * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateCancelWithdrawalGetCall(String currency, BigDecimal id, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -947,6 +1092,11 @@ private okhttp3.Call privateCancelWithdrawalGetValidateBeforeCall(String currenc * @param id The withdrawal id (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateCancelWithdrawalGet(String currency, BigDecimal id) throws ApiException { ApiResponse localVarResp = privateCancelWithdrawalGetWithHttpInfo(currency, id); @@ -960,6 +1110,11 @@ public Object privateCancelWithdrawalGet(String currency, BigDecimal id) throws * @param id The withdrawal id (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateCancelWithdrawalGetWithHttpInfo(String currency, BigDecimal id) throws ApiException { okhttp3.Call localVarCall = privateCancelWithdrawalGetValidateBeforeCall(currency, id, null); @@ -975,6 +1130,11 @@ public ApiResponse privateCancelWithdrawalGetWithHttpInfo(String currenc * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateCancelWithdrawalGetAsync(String currency, BigDecimal id, final ApiCallback _callback) throws ApiException { @@ -990,6 +1150,11 @@ public okhttp3.Call privateCancelWithdrawalGetAsync(String currency, BigDecimal * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateChangeSubaccountNameGetCall(Integer sid, String name, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1053,6 +1218,11 @@ private okhttp3.Call privateChangeSubaccountNameGetValidateBeforeCall(Integer si * @param name The new user name (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateChangeSubaccountNameGet(Integer sid, String name) throws ApiException { ApiResponse localVarResp = privateChangeSubaccountNameGetWithHttpInfo(sid, name); @@ -1066,6 +1236,11 @@ public Object privateChangeSubaccountNameGet(Integer sid, String name) throws Ap * @param name The new user name (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateChangeSubaccountNameGetWithHttpInfo(Integer sid, String name) throws ApiException { okhttp3.Call localVarCall = privateChangeSubaccountNameGetValidateBeforeCall(sid, name, null); @@ -1081,6 +1256,11 @@ public ApiResponse privateChangeSubaccountNameGetWithHttpInfo(Integer si * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateChangeSubaccountNameGetAsync(Integer sid, String name, final ApiCallback _callback) throws ApiException { @@ -1097,6 +1277,11 @@ public okhttp3.Call privateChangeSubaccountNameGetAsync(Integer sid, String name * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateClosePositionGetCall(String instrumentName, String type, BigDecimal price, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1165,6 +1350,11 @@ private okhttp3.Call privateClosePositionGetValidateBeforeCall(String instrument * @param price Optional price for limit order. (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateClosePositionGet(String instrumentName, String type, BigDecimal price) throws ApiException { ApiResponse localVarResp = privateClosePositionGetWithHttpInfo(instrumentName, type, price); @@ -1179,6 +1369,11 @@ public Object privateClosePositionGet(String instrumentName, String type, BigDec * @param price Optional price for limit order. (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateClosePositionGetWithHttpInfo(String instrumentName, String type, BigDecimal price) throws ApiException { okhttp3.Call localVarCall = privateClosePositionGetValidateBeforeCall(instrumentName, type, price, null); @@ -1195,6 +1390,11 @@ public ApiResponse privateClosePositionGetWithHttpInfo(String instrument * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateClosePositionGetAsync(String instrumentName, String type, BigDecimal price, final ApiCallback _callback) throws ApiException { @@ -1209,6 +1409,11 @@ public okhttp3.Call privateClosePositionGetAsync(String instrumentName, String t * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateCreateDepositAddressGetCall(String currency, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1262,6 +1467,11 @@ private okhttp3.Call privateCreateDepositAddressGetValidateBeforeCall(String cur * @param currency The currency symbol (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateCreateDepositAddressGet(String currency) throws ApiException { ApiResponse localVarResp = privateCreateDepositAddressGetWithHttpInfo(currency); @@ -1274,6 +1484,11 @@ public Object privateCreateDepositAddressGet(String currency) throws ApiExceptio * @param currency The currency symbol (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateCreateDepositAddressGetWithHttpInfo(String currency) throws ApiException { okhttp3.Call localVarCall = privateCreateDepositAddressGetValidateBeforeCall(currency, null); @@ -1288,6 +1503,11 @@ public ApiResponse privateCreateDepositAddressGetWithHttpInfo(String cur * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateCreateDepositAddressGetAsync(String currency, final ApiCallback _callback) throws ApiException { @@ -1301,6 +1521,11 @@ public okhttp3.Call privateCreateDepositAddressGetAsync(String currency, final A * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateCreateSubaccountGetCall(final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1344,6 +1569,11 @@ private okhttp3.Call privateCreateSubaccountGetValidateBeforeCall(final ApiCallb * * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateCreateSubaccountGet() throws ApiException { ApiResponse localVarResp = privateCreateSubaccountGetWithHttpInfo(); @@ -1355,6 +1585,11 @@ public Object privateCreateSubaccountGet() throws ApiException { * * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateCreateSubaccountGetWithHttpInfo() throws ApiException { okhttp3.Call localVarCall = privateCreateSubaccountGetValidateBeforeCall(null); @@ -1368,6 +1603,11 @@ public ApiResponse privateCreateSubaccountGetWithHttpInfo() throws ApiEx * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateCreateSubaccountGetAsync(final ApiCallback _callback) throws ApiException { @@ -1382,6 +1622,11 @@ public okhttp3.Call privateCreateSubaccountGetAsync(final ApiCallback _c * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateDisableTfaForSubaccountGetCall(Integer sid, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1435,6 +1680,11 @@ private okhttp3.Call privateDisableTfaForSubaccountGetValidateBeforeCall(Integer * @param sid The user id for the subaccount (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateDisableTfaForSubaccountGet(Integer sid) throws ApiException { ApiResponse localVarResp = privateDisableTfaForSubaccountGetWithHttpInfo(sid); @@ -1447,6 +1697,11 @@ public Object privateDisableTfaForSubaccountGet(Integer sid) throws ApiException * @param sid The user id for the subaccount (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateDisableTfaForSubaccountGetWithHttpInfo(Integer sid) throws ApiException { okhttp3.Call localVarCall = privateDisableTfaForSubaccountGetValidateBeforeCall(sid, null); @@ -1461,6 +1716,11 @@ public ApiResponse privateDisableTfaForSubaccountGetWithHttpInfo(Integer * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateDisableTfaForSubaccountGetAsync(Integer sid, final ApiCallback _callback) throws ApiException { @@ -1476,6 +1736,11 @@ public okhttp3.Call privateDisableTfaForSubaccountGetAsync(Integer sid, final Ap * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateDisableTfaWithRecoveryCodeGetCall(String password, String code, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1539,6 +1804,11 @@ private okhttp3.Call privateDisableTfaWithRecoveryCodeGetValidateBeforeCall(Stri * @param code One time recovery code (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateDisableTfaWithRecoveryCodeGet(String password, String code) throws ApiException { ApiResponse localVarResp = privateDisableTfaWithRecoveryCodeGetWithHttpInfo(password, code); @@ -1552,6 +1822,11 @@ public Object privateDisableTfaWithRecoveryCodeGet(String password, String code) * @param code One time recovery code (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateDisableTfaWithRecoveryCodeGetWithHttpInfo(String password, String code) throws ApiException { okhttp3.Call localVarCall = privateDisableTfaWithRecoveryCodeGetValidateBeforeCall(password, code, null); @@ -1567,6 +1842,11 @@ public ApiResponse privateDisableTfaWithRecoveryCodeGetWithHttpInfo(Stri * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateDisableTfaWithRecoveryCodeGetAsync(String password, String code, final ApiCallback _callback) throws ApiException { @@ -1586,6 +1866,11 @@ public okhttp3.Call privateDisableTfaWithRecoveryCodeGetAsync(String password, S * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateEditGetCall(String orderId, BigDecimal amount, BigDecimal price, Boolean postOnly, String advanced, BigDecimal stopPrice, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1674,6 +1959,11 @@ private okhttp3.Call privateEditGetValidateBeforeCall(String orderId, BigDecimal * @param stopPrice Stop price, required for stop limit orders (Only for stop orders) (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateEditGet(String orderId, BigDecimal amount, BigDecimal price, Boolean postOnly, String advanced, BigDecimal stopPrice) throws ApiException { ApiResponse localVarResp = privateEditGetWithHttpInfo(orderId, amount, price, postOnly, advanced, stopPrice); @@ -1691,6 +1981,11 @@ public Object privateEditGet(String orderId, BigDecimal amount, BigDecimal price * @param stopPrice Stop price, required for stop limit orders (Only for stop orders) (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateEditGetWithHttpInfo(String orderId, BigDecimal amount, BigDecimal price, Boolean postOnly, String advanced, BigDecimal stopPrice) throws ApiException { okhttp3.Call localVarCall = privateEditGetValidateBeforeCall(orderId, amount, price, postOnly, advanced, stopPrice, null); @@ -1710,6 +2005,11 @@ public ApiResponse privateEditGetWithHttpInfo(String orderId, BigDecimal * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateEditGetAsync(String orderId, BigDecimal amount, BigDecimal price, Boolean postOnly, String advanced, BigDecimal stopPrice, final ApiCallback _callback) throws ApiException { @@ -1725,6 +2025,11 @@ public okhttp3.Call privateEditGetAsync(String orderId, BigDecimal amount, BigDe * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetAccountSummaryGetCall(String currency, Boolean extended, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1783,6 +2088,11 @@ private okhttp3.Call privateGetAccountSummaryGetValidateBeforeCall(String curren * @param extended Include additional fields (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetAccountSummaryGet(String currency, Boolean extended) throws ApiException { ApiResponse localVarResp = privateGetAccountSummaryGetWithHttpInfo(currency, extended); @@ -1796,6 +2106,11 @@ public Object privateGetAccountSummaryGet(String currency, Boolean extended) thr * @param extended Include additional fields (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetAccountSummaryGetWithHttpInfo(String currency, Boolean extended) throws ApiException { okhttp3.Call localVarCall = privateGetAccountSummaryGetValidateBeforeCall(currency, extended, null); @@ -1811,6 +2126,11 @@ public ApiResponse privateGetAccountSummaryGetWithHttpInfo(String curren * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetAccountSummaryGetAsync(String currency, Boolean extended, final ApiCallback _callback) throws ApiException { @@ -1826,6 +2146,11 @@ public okhttp3.Call privateGetAccountSummaryGetAsync(String currency, Boolean ex * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetAddressBookGetCall(String currency, String type, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1889,6 +2214,11 @@ private okhttp3.Call privateGetAddressBookGetValidateBeforeCall(String currency, * @param type Address book type (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetAddressBookGet(String currency, String type) throws ApiException { ApiResponse localVarResp = privateGetAddressBookGetWithHttpInfo(currency, type); @@ -1902,6 +2232,11 @@ public Object privateGetAddressBookGet(String currency, String type) throws ApiE * @param type Address book type (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetAddressBookGetWithHttpInfo(String currency, String type) throws ApiException { okhttp3.Call localVarCall = privateGetAddressBookGetValidateBeforeCall(currency, type, null); @@ -1917,6 +2252,11 @@ public ApiResponse privateGetAddressBookGetWithHttpInfo(String currency, * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetAddressBookGetAsync(String currency, String type, final ApiCallback _callback) throws ApiException { @@ -1931,6 +2271,11 @@ public okhttp3.Call privateGetAddressBookGetAsync(String currency, String type, * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetCurrentDepositAddressGetCall(String currency, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1984,6 +2329,11 @@ private okhttp3.Call privateGetCurrentDepositAddressGetValidateBeforeCall(String * @param currency The currency symbol (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetCurrentDepositAddressGet(String currency) throws ApiException { ApiResponse localVarResp = privateGetCurrentDepositAddressGetWithHttpInfo(currency); @@ -1996,6 +2346,11 @@ public Object privateGetCurrentDepositAddressGet(String currency) throws ApiExce * @param currency The currency symbol (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetCurrentDepositAddressGetWithHttpInfo(String currency) throws ApiException { okhttp3.Call localVarCall = privateGetCurrentDepositAddressGetValidateBeforeCall(currency, null); @@ -2010,6 +2365,11 @@ public ApiResponse privateGetCurrentDepositAddressGetWithHttpInfo(String * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetCurrentDepositAddressGetAsync(String currency, final ApiCallback _callback) throws ApiException { @@ -2026,6 +2386,11 @@ public okhttp3.Call privateGetCurrentDepositAddressGetAsync(String currency, fin * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetDepositsGetCall(String currency, Integer count, Integer offset, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -2089,6 +2454,11 @@ private okhttp3.Call privateGetDepositsGetValidateBeforeCall(String currency, In * @param offset The offset for pagination, default - `0` (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetDepositsGet(String currency, Integer count, Integer offset) throws ApiException { ApiResponse localVarResp = privateGetDepositsGetWithHttpInfo(currency, count, offset); @@ -2103,6 +2473,11 @@ public Object privateGetDepositsGet(String currency, Integer count, Integer offs * @param offset The offset for pagination, default - `0` (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetDepositsGetWithHttpInfo(String currency, Integer count, Integer offset) throws ApiException { okhttp3.Call localVarCall = privateGetDepositsGetValidateBeforeCall(currency, count, offset, null); @@ -2119,6 +2494,11 @@ public ApiResponse privateGetDepositsGetWithHttpInfo(String currency, In * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetDepositsGetAsync(String currency, Integer count, Integer offset, final ApiCallback _callback) throws ApiException { @@ -2132,6 +2512,11 @@ public okhttp3.Call privateGetDepositsGetAsync(String currency, Integer count, I * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetEmailLanguageGetCall(final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -2175,6 +2560,11 @@ private okhttp3.Call privateGetEmailLanguageGetValidateBeforeCall(final ApiCallb * * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetEmailLanguageGet() throws ApiException { ApiResponse localVarResp = privateGetEmailLanguageGetWithHttpInfo(); @@ -2186,6 +2576,11 @@ public Object privateGetEmailLanguageGet() throws ApiException { * * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetEmailLanguageGetWithHttpInfo() throws ApiException { okhttp3.Call localVarCall = privateGetEmailLanguageGetValidateBeforeCall(null); @@ -2199,6 +2594,11 @@ public ApiResponse privateGetEmailLanguageGetWithHttpInfo() throws ApiEx * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetEmailLanguageGetAsync(final ApiCallback _callback) throws ApiException { @@ -2215,6 +2615,11 @@ public okhttp3.Call privateGetEmailLanguageGetAsync(final ApiCallback _c * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetMarginsGetCall(String instrumentName, BigDecimal amount, BigDecimal price, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -2288,6 +2693,11 @@ private okhttp3.Call privateGetMarginsGetValidateBeforeCall(String instrumentNam * @param price Price (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetMarginsGet(String instrumentName, BigDecimal amount, BigDecimal price) throws ApiException { ApiResponse localVarResp = privateGetMarginsGetWithHttpInfo(instrumentName, amount, price); @@ -2302,6 +2712,11 @@ public Object privateGetMarginsGet(String instrumentName, BigDecimal amount, Big * @param price Price (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetMarginsGetWithHttpInfo(String instrumentName, BigDecimal amount, BigDecimal price) throws ApiException { okhttp3.Call localVarCall = privateGetMarginsGetValidateBeforeCall(instrumentName, amount, price, null); @@ -2318,6 +2733,11 @@ public ApiResponse privateGetMarginsGetWithHttpInfo(String instrumentNam * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetMarginsGetAsync(String instrumentName, BigDecimal amount, BigDecimal price, final ApiCallback _callback) throws ApiException { @@ -2331,6 +2751,11 @@ public okhttp3.Call privateGetMarginsGetAsync(String instrumentName, BigDecimal * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetNewAnnouncementsGetCall(final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -2374,6 +2799,11 @@ private okhttp3.Call privateGetNewAnnouncementsGetValidateBeforeCall(final ApiCa * * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetNewAnnouncementsGet() throws ApiException { ApiResponse localVarResp = privateGetNewAnnouncementsGetWithHttpInfo(); @@ -2385,6 +2815,11 @@ public Object privateGetNewAnnouncementsGet() throws ApiException { * * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetNewAnnouncementsGetWithHttpInfo() throws ApiException { okhttp3.Call localVarCall = privateGetNewAnnouncementsGetValidateBeforeCall(null); @@ -2398,6 +2833,11 @@ public ApiResponse privateGetNewAnnouncementsGetWithHttpInfo() throws Ap * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetNewAnnouncementsGetAsync(final ApiCallback _callback) throws ApiException { @@ -2414,6 +2854,11 @@ public okhttp3.Call privateGetNewAnnouncementsGetAsync(final ApiCallback * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetOpenOrdersByCurrencyGetCall(String currency, String kind, String type, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -2477,6 +2922,11 @@ private okhttp3.Call privateGetOpenOrdersByCurrencyGetValidateBeforeCall(String * @param type Order type, default - `all` (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetOpenOrdersByCurrencyGet(String currency, String kind, String type) throws ApiException { ApiResponse localVarResp = privateGetOpenOrdersByCurrencyGetWithHttpInfo(currency, kind, type); @@ -2491,6 +2941,11 @@ public Object privateGetOpenOrdersByCurrencyGet(String currency, String kind, St * @param type Order type, default - `all` (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetOpenOrdersByCurrencyGetWithHttpInfo(String currency, String kind, String type) throws ApiException { okhttp3.Call localVarCall = privateGetOpenOrdersByCurrencyGetValidateBeforeCall(currency, kind, type, null); @@ -2507,6 +2962,11 @@ public ApiResponse privateGetOpenOrdersByCurrencyGetWithHttpInfo(String * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetOpenOrdersByCurrencyGetAsync(String currency, String kind, String type, final ApiCallback _callback) throws ApiException { @@ -2522,6 +2982,11 @@ public okhttp3.Call privateGetOpenOrdersByCurrencyGetAsync(String currency, Stri * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetOpenOrdersByInstrumentGetCall(String instrumentName, String type, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -2580,6 +3045,11 @@ private okhttp3.Call privateGetOpenOrdersByInstrumentGetValidateBeforeCall(Strin * @param type Order type, default - `all` (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetOpenOrdersByInstrumentGet(String instrumentName, String type) throws ApiException { ApiResponse localVarResp = privateGetOpenOrdersByInstrumentGetWithHttpInfo(instrumentName, type); @@ -2593,6 +3063,11 @@ public Object privateGetOpenOrdersByInstrumentGet(String instrumentName, String * @param type Order type, default - `all` (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetOpenOrdersByInstrumentGetWithHttpInfo(String instrumentName, String type) throws ApiException { okhttp3.Call localVarCall = privateGetOpenOrdersByInstrumentGetValidateBeforeCall(instrumentName, type, null); @@ -2608,6 +3083,11 @@ public ApiResponse privateGetOpenOrdersByInstrumentGetWithHttpInfo(Strin * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetOpenOrdersByInstrumentGetAsync(String instrumentName, String type, final ApiCallback _callback) throws ApiException { @@ -2627,6 +3107,11 @@ public okhttp3.Call privateGetOpenOrdersByInstrumentGetAsync(String instrumentNa * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetOrderHistoryByCurrencyGetCall(String currency, String kind, Integer count, Integer offset, Boolean includeOld, Boolean includeUnfilled, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -2705,6 +3190,11 @@ private okhttp3.Call privateGetOrderHistoryByCurrencyGetValidateBeforeCall(Strin * @param includeUnfilled Include in result fully unfilled closed orders, default - `false` (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetOrderHistoryByCurrencyGet(String currency, String kind, Integer count, Integer offset, Boolean includeOld, Boolean includeUnfilled) throws ApiException { ApiResponse localVarResp = privateGetOrderHistoryByCurrencyGetWithHttpInfo(currency, kind, count, offset, includeOld, includeUnfilled); @@ -2722,6 +3212,11 @@ public Object privateGetOrderHistoryByCurrencyGet(String currency, String kind, * @param includeUnfilled Include in result fully unfilled closed orders, default - `false` (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetOrderHistoryByCurrencyGetWithHttpInfo(String currency, String kind, Integer count, Integer offset, Boolean includeOld, Boolean includeUnfilled) throws ApiException { okhttp3.Call localVarCall = privateGetOrderHistoryByCurrencyGetValidateBeforeCall(currency, kind, count, offset, includeOld, includeUnfilled, null); @@ -2741,6 +3236,11 @@ public ApiResponse privateGetOrderHistoryByCurrencyGetWithHttpInfo(Strin * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetOrderHistoryByCurrencyGetAsync(String currency, String kind, Integer count, Integer offset, Boolean includeOld, Boolean includeUnfilled, final ApiCallback _callback) throws ApiException { @@ -2759,6 +3259,11 @@ public okhttp3.Call privateGetOrderHistoryByCurrencyGetAsync(String currency, St * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetOrderHistoryByInstrumentGetCall(String instrumentName, Integer count, Integer offset, Boolean includeOld, Boolean includeUnfilled, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -2832,6 +3337,11 @@ private okhttp3.Call privateGetOrderHistoryByInstrumentGetValidateBeforeCall(Str * @param includeUnfilled Include in result fully unfilled closed orders, default - `false` (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetOrderHistoryByInstrumentGet(String instrumentName, Integer count, Integer offset, Boolean includeOld, Boolean includeUnfilled) throws ApiException { ApiResponse localVarResp = privateGetOrderHistoryByInstrumentGetWithHttpInfo(instrumentName, count, offset, includeOld, includeUnfilled); @@ -2848,6 +3358,11 @@ public Object privateGetOrderHistoryByInstrumentGet(String instrumentName, Integ * @param includeUnfilled Include in result fully unfilled closed orders, default - `false` (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetOrderHistoryByInstrumentGetWithHttpInfo(String instrumentName, Integer count, Integer offset, Boolean includeOld, Boolean includeUnfilled) throws ApiException { okhttp3.Call localVarCall = privateGetOrderHistoryByInstrumentGetValidateBeforeCall(instrumentName, count, offset, includeOld, includeUnfilled, null); @@ -2866,6 +3381,11 @@ public ApiResponse privateGetOrderHistoryByInstrumentGetWithHttpInfo(Str * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetOrderHistoryByInstrumentGetAsync(String instrumentName, Integer count, Integer offset, Boolean includeOld, Boolean includeUnfilled, final ApiCallback _callback) throws ApiException { @@ -2880,6 +3400,11 @@ public okhttp3.Call privateGetOrderHistoryByInstrumentGetAsync(String instrument * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetOrderMarginByIdsGetCall(List ids, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -2933,6 +3458,11 @@ private okhttp3.Call privateGetOrderMarginByIdsGetValidateBeforeCall(List + Status Code Description Response Headers + 200 - + */ public Object privateGetOrderMarginByIdsGet(List ids) throws ApiException { ApiResponse localVarResp = privateGetOrderMarginByIdsGetWithHttpInfo(ids); @@ -2945,6 +3475,11 @@ public Object privateGetOrderMarginByIdsGet(List ids) throws ApiExceptio * @param ids Ids of orders (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetOrderMarginByIdsGetWithHttpInfo(List ids) throws ApiException { okhttp3.Call localVarCall = privateGetOrderMarginByIdsGetValidateBeforeCall(ids, null); @@ -2959,6 +3494,11 @@ public ApiResponse privateGetOrderMarginByIdsGetWithHttpInfo(List + Status Code Description Response Headers + 200 - + */ public okhttp3.Call privateGetOrderMarginByIdsGetAsync(List ids, final ApiCallback _callback) throws ApiException { @@ -2973,6 +3513,12 @@ public okhttp3.Call privateGetOrderMarginByIdsGetAsync(List ids, final A * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + +
Status Code Description Response Headers
200 ok response -
400 result when used via rest/HTTP -
*/ public okhttp3.Call privateGetOrderStateGetCall(String orderId, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -3026,6 +3572,12 @@ private okhttp3.Call privateGetOrderStateGetValidateBeforeCall(String orderId, f * @param orderId The order id (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
Status Code Description Response Headers
200 ok response -
400 result when used via rest/HTTP -
*/ public Object privateGetOrderStateGet(String orderId) throws ApiException { ApiResponse localVarResp = privateGetOrderStateGetWithHttpInfo(orderId); @@ -3038,6 +3590,12 @@ public Object privateGetOrderStateGet(String orderId) throws ApiException { * @param orderId The order id (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
Status Code Description Response Headers
200 ok response -
400 result when used via rest/HTTP -
*/ public ApiResponse privateGetOrderStateGetWithHttpInfo(String orderId) throws ApiException { okhttp3.Call localVarCall = privateGetOrderStateGetValidateBeforeCall(orderId, null); @@ -3052,6 +3610,12 @@ public ApiResponse privateGetOrderStateGetWithHttpInfo(String orderId) t * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + +
Status Code Description Response Headers
200 ok response -
400 result when used via rest/HTTP -
*/ public okhttp3.Call privateGetOrderStateGetAsync(String orderId, final ApiCallback _callback) throws ApiException { @@ -3066,6 +3630,12 @@ public okhttp3.Call privateGetOrderStateGetAsync(String orderId, final ApiCallba * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + +
Status Code Description Response Headers
200 When successful returns position -
400 When some error occurs -
*/ public okhttp3.Call privateGetPositionGetCall(String instrumentName, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -3119,6 +3689,12 @@ private okhttp3.Call privateGetPositionGetValidateBeforeCall(String instrumentNa * @param instrumentName Instrument name (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
Status Code Description Response Headers
200 When successful returns position -
400 When some error occurs -
*/ public Object privateGetPositionGet(String instrumentName) throws ApiException { ApiResponse localVarResp = privateGetPositionGetWithHttpInfo(instrumentName); @@ -3131,6 +3707,12 @@ public Object privateGetPositionGet(String instrumentName) throws ApiException { * @param instrumentName Instrument name (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
Status Code Description Response Headers
200 When successful returns position -
400 When some error occurs -
*/ public ApiResponse privateGetPositionGetWithHttpInfo(String instrumentName) throws ApiException { okhttp3.Call localVarCall = privateGetPositionGetValidateBeforeCall(instrumentName, null); @@ -3145,6 +3727,12 @@ public ApiResponse privateGetPositionGetWithHttpInfo(String instrumentNa * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + +
Status Code Description Response Headers
200 When successful returns position -
400 When some error occurs -
*/ public okhttp3.Call privateGetPositionGetAsync(String instrumentName, final ApiCallback _callback) throws ApiException { @@ -3160,6 +3748,12 @@ public okhttp3.Call privateGetPositionGetAsync(String instrumentName, final ApiC * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + +
Status Code Description Response Headers
200 When successful returns array of positions -
400 When some error occurs -
*/ public okhttp3.Call privateGetPositionsGetCall(String currency, String kind, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -3218,6 +3812,12 @@ private okhttp3.Call privateGetPositionsGetValidateBeforeCall(String currency, S * @param kind Kind filter on positions (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
Status Code Description Response Headers
200 When successful returns array of positions -
400 When some error occurs -
*/ public Object privateGetPositionsGet(String currency, String kind) throws ApiException { ApiResponse localVarResp = privateGetPositionsGetWithHttpInfo(currency, kind); @@ -3231,6 +3831,12 @@ public Object privateGetPositionsGet(String currency, String kind) throws ApiExc * @param kind Kind filter on positions (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
Status Code Description Response Headers
200 When successful returns array of positions -
400 When some error occurs -
*/ public ApiResponse privateGetPositionsGetWithHttpInfo(String currency, String kind) throws ApiException { okhttp3.Call localVarCall = privateGetPositionsGetValidateBeforeCall(currency, kind, null); @@ -3246,6 +3852,12 @@ public ApiResponse privateGetPositionsGetWithHttpInfo(String currency, S * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + +
Status Code Description Response Headers
200 When successful returns array of positions -
400 When some error occurs -
*/ public okhttp3.Call privateGetPositionsGetAsync(String currency, String kind, final ApiCallback _callback) throws ApiException { @@ -3262,6 +3874,11 @@ public okhttp3.Call privateGetPositionsGetAsync(String currency, String kind, fi * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetSettlementHistoryByCurrencyGetCall(String currency, String type, Integer count, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -3325,6 +3942,11 @@ private okhttp3.Call privateGetSettlementHistoryByCurrencyGetValidateBeforeCall( * @param count Number of requested items, default - `20` (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetSettlementHistoryByCurrencyGet(String currency, String type, Integer count) throws ApiException { ApiResponse localVarResp = privateGetSettlementHistoryByCurrencyGetWithHttpInfo(currency, type, count); @@ -3339,6 +3961,11 @@ public Object privateGetSettlementHistoryByCurrencyGet(String currency, String t * @param count Number of requested items, default - `20` (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetSettlementHistoryByCurrencyGetWithHttpInfo(String currency, String type, Integer count) throws ApiException { okhttp3.Call localVarCall = privateGetSettlementHistoryByCurrencyGetValidateBeforeCall(currency, type, count, null); @@ -3355,6 +3982,11 @@ public ApiResponse privateGetSettlementHistoryByCurrencyGetWithHttpInfo( * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetSettlementHistoryByCurrencyGetAsync(String currency, String type, Integer count, final ApiCallback _callback) throws ApiException { @@ -3371,6 +4003,11 @@ public okhttp3.Call privateGetSettlementHistoryByCurrencyGetAsync(String currenc * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetSettlementHistoryByInstrumentGetCall(String instrumentName, String type, Integer count, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -3434,6 +4071,11 @@ private okhttp3.Call privateGetSettlementHistoryByInstrumentGetValidateBeforeCal * @param count Number of requested items, default - `20` (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetSettlementHistoryByInstrumentGet(String instrumentName, String type, Integer count) throws ApiException { ApiResponse localVarResp = privateGetSettlementHistoryByInstrumentGetWithHttpInfo(instrumentName, type, count); @@ -3448,6 +4090,11 @@ public Object privateGetSettlementHistoryByInstrumentGet(String instrumentName, * @param count Number of requested items, default - `20` (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetSettlementHistoryByInstrumentGetWithHttpInfo(String instrumentName, String type, Integer count) throws ApiException { okhttp3.Call localVarCall = privateGetSettlementHistoryByInstrumentGetValidateBeforeCall(instrumentName, type, count, null); @@ -3464,6 +4111,11 @@ public ApiResponse privateGetSettlementHistoryByInstrumentGetWithHttpInf * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetSettlementHistoryByInstrumentGetAsync(String instrumentName, String type, Integer count, final ApiCallback _callback) throws ApiException { @@ -3478,6 +4130,12 @@ public okhttp3.Call privateGetSettlementHistoryByInstrumentGetAsync(String instr * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + +
Status Code Description Response Headers
200 ok response -
401 not authorised -
*/ public okhttp3.Call privateGetSubaccountsGetCall(Boolean withPortfolio, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -3526,6 +4184,12 @@ private okhttp3.Call privateGetSubaccountsGetValidateBeforeCall(Boolean withPort * @param withPortfolio (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
Status Code Description Response Headers
200 ok response -
401 not authorised -
*/ public Object privateGetSubaccountsGet(Boolean withPortfolio) throws ApiException { ApiResponse localVarResp = privateGetSubaccountsGetWithHttpInfo(withPortfolio); @@ -3538,6 +4202,12 @@ public Object privateGetSubaccountsGet(Boolean withPortfolio) throws ApiExceptio * @param withPortfolio (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
Status Code Description Response Headers
200 ok response -
401 not authorised -
*/ public ApiResponse privateGetSubaccountsGetWithHttpInfo(Boolean withPortfolio) throws ApiException { okhttp3.Call localVarCall = privateGetSubaccountsGetValidateBeforeCall(withPortfolio, null); @@ -3552,6 +4222,12 @@ public ApiResponse privateGetSubaccountsGetWithHttpInfo(Boolean withPort * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + +
Status Code Description Response Headers
200 ok response -
401 not authorised -
*/ public okhttp3.Call privateGetSubaccountsGetAsync(Boolean withPortfolio, final ApiCallback _callback) throws ApiException { @@ -3568,6 +4244,11 @@ public okhttp3.Call privateGetSubaccountsGetAsync(Boolean withPortfolio, final A * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetTransfersGetCall(String currency, Integer count, Integer offset, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -3631,6 +4312,11 @@ private okhttp3.Call privateGetTransfersGetValidateBeforeCall(String currency, I * @param offset The offset for pagination, default - `0` (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetTransfersGet(String currency, Integer count, Integer offset) throws ApiException { ApiResponse localVarResp = privateGetTransfersGetWithHttpInfo(currency, count, offset); @@ -3645,6 +4331,11 @@ public Object privateGetTransfersGet(String currency, Integer count, Integer off * @param offset The offset for pagination, default - `0` (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetTransfersGetWithHttpInfo(String currency, Integer count, Integer offset) throws ApiException { okhttp3.Call localVarCall = privateGetTransfersGetValidateBeforeCall(currency, count, offset, null); @@ -3661,6 +4352,11 @@ public ApiResponse privateGetTransfersGetWithHttpInfo(String currency, I * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetTransfersGetAsync(String currency, Integer count, Integer offset, final ApiCallback _callback) throws ApiException { @@ -3681,6 +4377,11 @@ public okhttp3.Call privateGetTransfersGetAsync(String currency, Integer count, * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetUserTradesByCurrencyAndTimeGetCall(String currency, Integer startTimestamp, Integer endTimestamp, String kind, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -3774,6 +4475,11 @@ private okhttp3.Call privateGetUserTradesByCurrencyAndTimeGetValidateBeforeCall( * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetUserTradesByCurrencyAndTimeGet(String currency, Integer startTimestamp, Integer endTimestamp, String kind, Integer count, Boolean includeOld, String sorting) throws ApiException { ApiResponse localVarResp = privateGetUserTradesByCurrencyAndTimeGetWithHttpInfo(currency, startTimestamp, endTimestamp, kind, count, includeOld, sorting); @@ -3792,6 +4498,11 @@ public Object privateGetUserTradesByCurrencyAndTimeGet(String currency, Integer * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetUserTradesByCurrencyAndTimeGetWithHttpInfo(String currency, Integer startTimestamp, Integer endTimestamp, String kind, Integer count, Boolean includeOld, String sorting) throws ApiException { okhttp3.Call localVarCall = privateGetUserTradesByCurrencyAndTimeGetValidateBeforeCall(currency, startTimestamp, endTimestamp, kind, count, includeOld, sorting, null); @@ -3812,6 +4523,11 @@ public ApiResponse privateGetUserTradesByCurrencyAndTimeGetWithHttpInfo( * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetUserTradesByCurrencyAndTimeGetAsync(String currency, Integer startTimestamp, Integer endTimestamp, String kind, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { @@ -3832,6 +4548,11 @@ public okhttp3.Call privateGetUserTradesByCurrencyAndTimeGetAsync(String currenc * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetUserTradesByCurrencyGetCall(String currency, String kind, String startId, String endId, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -3915,6 +4636,11 @@ private okhttp3.Call privateGetUserTradesByCurrencyGetValidateBeforeCall(String * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetUserTradesByCurrencyGet(String currency, String kind, String startId, String endId, Integer count, Boolean includeOld, String sorting) throws ApiException { ApiResponse localVarResp = privateGetUserTradesByCurrencyGetWithHttpInfo(currency, kind, startId, endId, count, includeOld, sorting); @@ -3933,6 +4659,11 @@ public Object privateGetUserTradesByCurrencyGet(String currency, String kind, St * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetUserTradesByCurrencyGetWithHttpInfo(String currency, String kind, String startId, String endId, Integer count, Boolean includeOld, String sorting) throws ApiException { okhttp3.Call localVarCall = privateGetUserTradesByCurrencyGetValidateBeforeCall(currency, kind, startId, endId, count, includeOld, sorting, null); @@ -3953,6 +4684,11 @@ public ApiResponse privateGetUserTradesByCurrencyGetWithHttpInfo(String * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetUserTradesByCurrencyGetAsync(String currency, String kind, String startId, String endId, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { @@ -3972,6 +4708,11 @@ public okhttp3.Call privateGetUserTradesByCurrencyGetAsync(String currency, Stri * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetUserTradesByInstrumentAndTimeGetCall(String instrumentName, Integer startTimestamp, Integer endTimestamp, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -4060,6 +4801,11 @@ private okhttp3.Call privateGetUserTradesByInstrumentAndTimeGetValidateBeforeCal * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetUserTradesByInstrumentAndTimeGet(String instrumentName, Integer startTimestamp, Integer endTimestamp, Integer count, Boolean includeOld, String sorting) throws ApiException { ApiResponse localVarResp = privateGetUserTradesByInstrumentAndTimeGetWithHttpInfo(instrumentName, startTimestamp, endTimestamp, count, includeOld, sorting); @@ -4077,6 +4823,11 @@ public Object privateGetUserTradesByInstrumentAndTimeGet(String instrumentName, * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetUserTradesByInstrumentAndTimeGetWithHttpInfo(String instrumentName, Integer startTimestamp, Integer endTimestamp, Integer count, Boolean includeOld, String sorting) throws ApiException { okhttp3.Call localVarCall = privateGetUserTradesByInstrumentAndTimeGetValidateBeforeCall(instrumentName, startTimestamp, endTimestamp, count, includeOld, sorting, null); @@ -4096,6 +4847,11 @@ public ApiResponse privateGetUserTradesByInstrumentAndTimeGetWithHttpInf * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetUserTradesByInstrumentAndTimeGetAsync(String instrumentName, Integer startTimestamp, Integer endTimestamp, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { @@ -4115,6 +4871,11 @@ public okhttp3.Call privateGetUserTradesByInstrumentAndTimeGetAsync(String instr * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetUserTradesByInstrumentGetCall(String instrumentName, Integer startSeq, Integer endSeq, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -4193,6 +4954,11 @@ private okhttp3.Call privateGetUserTradesByInstrumentGetValidateBeforeCall(Strin * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetUserTradesByInstrumentGet(String instrumentName, Integer startSeq, Integer endSeq, Integer count, Boolean includeOld, String sorting) throws ApiException { ApiResponse localVarResp = privateGetUserTradesByInstrumentGetWithHttpInfo(instrumentName, startSeq, endSeq, count, includeOld, sorting); @@ -4210,6 +4976,11 @@ public Object privateGetUserTradesByInstrumentGet(String instrumentName, Integer * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetUserTradesByInstrumentGetWithHttpInfo(String instrumentName, Integer startSeq, Integer endSeq, Integer count, Boolean includeOld, String sorting) throws ApiException { okhttp3.Call localVarCall = privateGetUserTradesByInstrumentGetValidateBeforeCall(instrumentName, startSeq, endSeq, count, includeOld, sorting, null); @@ -4229,6 +5000,11 @@ public ApiResponse privateGetUserTradesByInstrumentGetWithHttpInfo(Strin * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetUserTradesByInstrumentGetAsync(String instrumentName, Integer startSeq, Integer endSeq, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { @@ -4244,6 +5020,11 @@ public okhttp3.Call privateGetUserTradesByInstrumentGetAsync(String instrumentNa * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetUserTradesByOrderGetCall(String orderId, String sorting, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -4302,6 +5083,11 @@ private okhttp3.Call privateGetUserTradesByOrderGetValidateBeforeCall(String ord * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetUserTradesByOrderGet(String orderId, String sorting) throws ApiException { ApiResponse localVarResp = privateGetUserTradesByOrderGetWithHttpInfo(orderId, sorting); @@ -4315,6 +5101,11 @@ public Object privateGetUserTradesByOrderGet(String orderId, String sorting) thr * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetUserTradesByOrderGetWithHttpInfo(String orderId, String sorting) throws ApiException { okhttp3.Call localVarCall = privateGetUserTradesByOrderGetValidateBeforeCall(orderId, sorting, null); @@ -4330,6 +5121,11 @@ public ApiResponse privateGetUserTradesByOrderGetWithHttpInfo(String ord * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetUserTradesByOrderGetAsync(String orderId, String sorting, final ApiCallback _callback) throws ApiException { @@ -4346,6 +5142,11 @@ public okhttp3.Call privateGetUserTradesByOrderGetAsync(String orderId, String s * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetWithdrawalsGetCall(String currency, Integer count, Integer offset, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -4409,6 +5210,11 @@ private okhttp3.Call privateGetWithdrawalsGetValidateBeforeCall(String currency, * @param offset The offset for pagination, default - `0` (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetWithdrawalsGet(String currency, Integer count, Integer offset) throws ApiException { ApiResponse localVarResp = privateGetWithdrawalsGetWithHttpInfo(currency, count, offset); @@ -4423,6 +5229,11 @@ public Object privateGetWithdrawalsGet(String currency, Integer count, Integer o * @param offset The offset for pagination, default - `0` (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetWithdrawalsGetWithHttpInfo(String currency, Integer count, Integer offset) throws ApiException { okhttp3.Call localVarCall = privateGetWithdrawalsGetValidateBeforeCall(currency, count, offset, null); @@ -4439,6 +5250,11 @@ public ApiResponse privateGetWithdrawalsGetWithHttpInfo(String currency, * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetWithdrawalsGetAsync(String currency, Integer count, Integer offset, final ApiCallback _callback) throws ApiException { @@ -4456,6 +5272,11 @@ public okhttp3.Call privateGetWithdrawalsGetAsync(String currency, Integer count * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateRemoveFromAddressBookGetCall(String currency, String type, String address, String tfa, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -4534,6 +5355,11 @@ private okhttp3.Call privateRemoveFromAddressBookGetValidateBeforeCall(String cu * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateRemoveFromAddressBookGet(String currency, String type, String address, String tfa) throws ApiException { ApiResponse localVarResp = privateRemoveFromAddressBookGetWithHttpInfo(currency, type, address, tfa); @@ -4549,6 +5375,11 @@ public Object privateRemoveFromAddressBookGet(String currency, String type, Stri * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateRemoveFromAddressBookGetWithHttpInfo(String currency, String type, String address, String tfa) throws ApiException { okhttp3.Call localVarCall = privateRemoveFromAddressBookGetValidateBeforeCall(currency, type, address, tfa, null); @@ -4566,6 +5397,11 @@ public ApiResponse privateRemoveFromAddressBookGetWithHttpInfo(String cu * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateRemoveFromAddressBookGetAsync(String currency, String type, String address, String tfa, final ApiCallback _callback) throws ApiException { @@ -4591,6 +5427,11 @@ public okhttp3.Call privateRemoveFromAddressBookGetAsync(String currency, String * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateSellGetCall(String instrumentName, BigDecimal amount, String type, String label, BigDecimal price, String timeInForce, BigDecimal maxShow, Boolean postOnly, Boolean reduceOnly, BigDecimal stopPrice, String trigger, String advanced, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -4704,6 +5545,11 @@ private okhttp3.Call privateSellGetValidateBeforeCall(String instrumentName, Big * @param advanced Advanced option order type. (Only for options) (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateSellGet(String instrumentName, BigDecimal amount, String type, String label, BigDecimal price, String timeInForce, BigDecimal maxShow, Boolean postOnly, Boolean reduceOnly, BigDecimal stopPrice, String trigger, String advanced) throws ApiException { ApiResponse localVarResp = privateSellGetWithHttpInfo(instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced); @@ -4727,6 +5573,11 @@ public Object privateSellGet(String instrumentName, BigDecimal amount, String ty * @param advanced Advanced option order type. (Only for options) (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateSellGetWithHttpInfo(String instrumentName, BigDecimal amount, String type, String label, BigDecimal price, String timeInForce, BigDecimal maxShow, Boolean postOnly, Boolean reduceOnly, BigDecimal stopPrice, String trigger, String advanced) throws ApiException { okhttp3.Call localVarCall = privateSellGetValidateBeforeCall(instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced, null); @@ -4752,6 +5603,11 @@ public ApiResponse privateSellGetWithHttpInfo(String instrumentName, Big * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateSellGetAsync(String instrumentName, BigDecimal amount, String type, String label, BigDecimal price, String timeInForce, BigDecimal maxShow, Boolean postOnly, Boolean reduceOnly, BigDecimal stopPrice, String trigger, String advanced, final ApiCallback _callback) throws ApiException { @@ -4766,6 +5622,11 @@ public okhttp3.Call privateSellGetAsync(String instrumentName, BigDecimal amount * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateSetAnnouncementAsReadGetCall(BigDecimal announcementId, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -4819,6 +5680,11 @@ private okhttp3.Call privateSetAnnouncementAsReadGetValidateBeforeCall(BigDecima * @param announcementId the ID of the announcement (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateSetAnnouncementAsReadGet(BigDecimal announcementId) throws ApiException { ApiResponse localVarResp = privateSetAnnouncementAsReadGetWithHttpInfo(announcementId); @@ -4831,6 +5697,11 @@ public Object privateSetAnnouncementAsReadGet(BigDecimal announcementId) throws * @param announcementId the ID of the announcement (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateSetAnnouncementAsReadGetWithHttpInfo(BigDecimal announcementId) throws ApiException { okhttp3.Call localVarCall = privateSetAnnouncementAsReadGetValidateBeforeCall(announcementId, null); @@ -4845,6 +5716,11 @@ public ApiResponse privateSetAnnouncementAsReadGetWithHttpInfo(BigDecima * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateSetAnnouncementAsReadGetAsync(BigDecimal announcementId, final ApiCallback _callback) throws ApiException { @@ -4860,6 +5736,11 @@ public okhttp3.Call privateSetAnnouncementAsReadGetAsync(BigDecimal announcement * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateSetEmailForSubaccountGetCall(Integer sid, String email, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -4923,6 +5804,11 @@ private okhttp3.Call privateSetEmailForSubaccountGetValidateBeforeCall(Integer s * @param email The email address for the subaccount (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateSetEmailForSubaccountGet(Integer sid, String email) throws ApiException { ApiResponse localVarResp = privateSetEmailForSubaccountGetWithHttpInfo(sid, email); @@ -4936,6 +5822,11 @@ public Object privateSetEmailForSubaccountGet(Integer sid, String email) throws * @param email The email address for the subaccount (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateSetEmailForSubaccountGetWithHttpInfo(Integer sid, String email) throws ApiException { okhttp3.Call localVarCall = privateSetEmailForSubaccountGetValidateBeforeCall(sid, email, null); @@ -4951,6 +5842,11 @@ public ApiResponse privateSetEmailForSubaccountGetWithHttpInfo(Integer s * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateSetEmailForSubaccountGetAsync(Integer sid, String email, final ApiCallback _callback) throws ApiException { @@ -4965,6 +5861,11 @@ public okhttp3.Call privateSetEmailForSubaccountGetAsync(Integer sid, String ema * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateSetEmailLanguageGetCall(String language, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -5018,6 +5919,11 @@ private okhttp3.Call privateSetEmailLanguageGetValidateBeforeCall(String languag * @param language The abbreviated language name. Valid values include `\"en\"`, `\"ko\"`, `\"zh\"` (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateSetEmailLanguageGet(String language) throws ApiException { ApiResponse localVarResp = privateSetEmailLanguageGetWithHttpInfo(language); @@ -5030,6 +5936,11 @@ public Object privateSetEmailLanguageGet(String language) throws ApiException { * @param language The abbreviated language name. Valid values include `\"en\"`, `\"ko\"`, `\"zh\"` (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateSetEmailLanguageGetWithHttpInfo(String language) throws ApiException { okhttp3.Call localVarCall = privateSetEmailLanguageGetValidateBeforeCall(language, null); @@ -5044,6 +5955,11 @@ public ApiResponse privateSetEmailLanguageGetWithHttpInfo(String languag * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateSetEmailLanguageGetAsync(String language, final ApiCallback _callback) throws ApiException { @@ -5059,6 +5975,11 @@ public okhttp3.Call privateSetEmailLanguageGetAsync(String language, final ApiCa * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateSetPasswordForSubaccountGetCall(Integer sid, String password, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -5122,6 +6043,11 @@ private okhttp3.Call privateSetPasswordForSubaccountGetValidateBeforeCall(Intege * @param password The password for the subaccount (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateSetPasswordForSubaccountGet(Integer sid, String password) throws ApiException { ApiResponse localVarResp = privateSetPasswordForSubaccountGetWithHttpInfo(sid, password); @@ -5135,6 +6061,11 @@ public Object privateSetPasswordForSubaccountGet(Integer sid, String password) t * @param password The password for the subaccount (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateSetPasswordForSubaccountGetWithHttpInfo(Integer sid, String password) throws ApiException { okhttp3.Call localVarCall = privateSetPasswordForSubaccountGetValidateBeforeCall(sid, password, null); @@ -5150,6 +6081,11 @@ public ApiResponse privateSetPasswordForSubaccountGetWithHttpInfo(Intege * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateSetPasswordForSubaccountGetAsync(Integer sid, String password, final ApiCallback _callback) throws ApiException { @@ -5166,6 +6102,11 @@ public okhttp3.Call privateSetPasswordForSubaccountGetAsync(Integer sid, String * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateSubmitTransferToSubaccountGetCall(String currency, BigDecimal amount, Integer destination, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -5239,6 +6180,11 @@ private okhttp3.Call privateSubmitTransferToSubaccountGetValidateBeforeCall(Stri * @param destination Id of destination subaccount (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateSubmitTransferToSubaccountGet(String currency, BigDecimal amount, Integer destination) throws ApiException { ApiResponse localVarResp = privateSubmitTransferToSubaccountGetWithHttpInfo(currency, amount, destination); @@ -5253,6 +6199,11 @@ public Object privateSubmitTransferToSubaccountGet(String currency, BigDecimal a * @param destination Id of destination subaccount (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateSubmitTransferToSubaccountGetWithHttpInfo(String currency, BigDecimal amount, Integer destination) throws ApiException { okhttp3.Call localVarCall = privateSubmitTransferToSubaccountGetValidateBeforeCall(currency, amount, destination, null); @@ -5269,6 +6220,11 @@ public ApiResponse privateSubmitTransferToSubaccountGetWithHttpInfo(Stri * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateSubmitTransferToSubaccountGetAsync(String currency, BigDecimal amount, Integer destination, final ApiCallback _callback) throws ApiException { @@ -5286,6 +6242,11 @@ public okhttp3.Call privateSubmitTransferToSubaccountGetAsync(String currency, B * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateSubmitTransferToUserGetCall(String currency, BigDecimal amount, String destination, String tfa, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -5364,6 +6325,11 @@ private okhttp3.Call privateSubmitTransferToUserGetValidateBeforeCall(String cur * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateSubmitTransferToUserGet(String currency, BigDecimal amount, String destination, String tfa) throws ApiException { ApiResponse localVarResp = privateSubmitTransferToUserGetWithHttpInfo(currency, amount, destination, tfa); @@ -5379,6 +6345,11 @@ public Object privateSubmitTransferToUserGet(String currency, BigDecimal amount, * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateSubmitTransferToUserGetWithHttpInfo(String currency, BigDecimal amount, String destination, String tfa) throws ApiException { okhttp3.Call localVarCall = privateSubmitTransferToUserGetValidateBeforeCall(currency, amount, destination, tfa, null); @@ -5396,6 +6367,11 @@ public ApiResponse privateSubmitTransferToUserGetWithHttpInfo(String cur * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateSubmitTransferToUserGetAsync(String currency, BigDecimal amount, String destination, String tfa, final ApiCallback _callback) throws ApiException { @@ -5411,6 +6387,11 @@ public okhttp3.Call privateSubmitTransferToUserGetAsync(String currency, BigDeci * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateToggleDepositAddressCreationGetCall(String currency, Boolean state, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -5474,6 +6455,11 @@ private okhttp3.Call privateToggleDepositAddressCreationGetValidateBeforeCall(St * @param state (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateToggleDepositAddressCreationGet(String currency, Boolean state) throws ApiException { ApiResponse localVarResp = privateToggleDepositAddressCreationGetWithHttpInfo(currency, state); @@ -5487,6 +6473,11 @@ public Object privateToggleDepositAddressCreationGet(String currency, Boolean st * @param state (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateToggleDepositAddressCreationGetWithHttpInfo(String currency, Boolean state) throws ApiException { okhttp3.Call localVarCall = privateToggleDepositAddressCreationGetValidateBeforeCall(currency, state, null); @@ -5502,6 +6493,11 @@ public ApiResponse privateToggleDepositAddressCreationGetWithHttpInfo(St * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateToggleDepositAddressCreationGetAsync(String currency, Boolean state, final ApiCallback _callback) throws ApiException { @@ -5517,6 +6513,11 @@ public okhttp3.Call privateToggleDepositAddressCreationGetAsync(String currency, * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateToggleNotificationsFromSubaccountGetCall(Integer sid, Boolean state, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -5580,6 +6581,11 @@ private okhttp3.Call privateToggleNotificationsFromSubaccountGetValidateBeforeCa * @param state enable (`true`) or disable (`false`) notifications (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateToggleNotificationsFromSubaccountGet(Integer sid, Boolean state) throws ApiException { ApiResponse localVarResp = privateToggleNotificationsFromSubaccountGetWithHttpInfo(sid, state); @@ -5593,6 +6599,11 @@ public Object privateToggleNotificationsFromSubaccountGet(Integer sid, Boolean s * @param state enable (`true`) or disable (`false`) notifications (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateToggleNotificationsFromSubaccountGetWithHttpInfo(Integer sid, Boolean state) throws ApiException { okhttp3.Call localVarCall = privateToggleNotificationsFromSubaccountGetValidateBeforeCall(sid, state, null); @@ -5608,6 +6619,11 @@ public ApiResponse privateToggleNotificationsFromSubaccountGetWithHttpIn * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateToggleNotificationsFromSubaccountGetAsync(Integer sid, Boolean state, final ApiCallback _callback) throws ApiException { @@ -5623,6 +6639,11 @@ public okhttp3.Call privateToggleNotificationsFromSubaccountGetAsync(Integer sid * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateToggleSubaccountLoginGetCall(Integer sid, String state, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -5686,6 +6707,11 @@ private okhttp3.Call privateToggleSubaccountLoginGetValidateBeforeCall(Integer s * @param state enable or disable login. (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateToggleSubaccountLoginGet(Integer sid, String state) throws ApiException { ApiResponse localVarResp = privateToggleSubaccountLoginGetWithHttpInfo(sid, state); @@ -5699,6 +6725,11 @@ public Object privateToggleSubaccountLoginGet(Integer sid, String state) throws * @param state enable or disable login. (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateToggleSubaccountLoginGetWithHttpInfo(Integer sid, String state) throws ApiException { okhttp3.Call localVarCall = privateToggleSubaccountLoginGetValidateBeforeCall(sid, state, null); @@ -5714,6 +6745,11 @@ public ApiResponse privateToggleSubaccountLoginGetWithHttpInfo(Integer s * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateToggleSubaccountLoginGetAsync(Integer sid, String state, final ApiCallback _callback) throws ApiException { @@ -5732,6 +6768,11 @@ public okhttp3.Call privateToggleSubaccountLoginGetAsync(Integer sid, String sta * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateWithdrawGetCall(String currency, String address, BigDecimal amount, String priority, String tfa, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -5815,6 +6856,11 @@ private okhttp3.Call privateWithdrawGetValidateBeforeCall(String currency, Strin * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateWithdrawGet(String currency, String address, BigDecimal amount, String priority, String tfa) throws ApiException { ApiResponse localVarResp = privateWithdrawGetWithHttpInfo(currency, address, amount, priority, tfa); @@ -5831,6 +6877,11 @@ public Object privateWithdrawGet(String currency, String address, BigDecimal amo * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateWithdrawGetWithHttpInfo(String currency, String address, BigDecimal amount, String priority, String tfa) throws ApiException { okhttp3.Call localVarCall = privateWithdrawGetValidateBeforeCall(currency, address, amount, priority, tfa, null); @@ -5849,6 +6900,11 @@ public ApiResponse privateWithdrawGetWithHttpInfo(String currency, Strin * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateWithdrawGetAsync(String currency, String address, BigDecimal amount, String priority, String tfa, final ApiCallback _callback) throws ApiException { diff --git a/java/src/main/java/org/openapitools/client/api/PublicApi.java b/java/src/main/java/org/openapitools/client/api/PublicApi.java index 42c3e30..279f54f 100644 --- a/java/src/main/java/org/openapitools/client/api/PublicApi.java +++ b/java/src/main/java/org/openapitools/client/api/PublicApi.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -70,6 +70,12 @@ public void setApiClient(ApiClient apiClient) { * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + +
Status Code Description Response Headers
200 ok response -
429 over limit -
*/ public okhttp3.Call publicAuthGetCall(String grantType, String username, String password, String clientId, String clientSecret, String refreshToken, String timestamp, String signature, String nonce, String state, String scope, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -208,6 +214,12 @@ private okhttp3.Call publicAuthGetValidateBeforeCall(String grantType, String us * @param scope Describes type of the access for assigned token, possible values: `connection`, `session`, `session:name`, `trade:[read, read_write, none]`, `wallet:[read, read_write, none]`, `account:[read, read_write, none]`, `expires:NUMBER` (token will expire after `NUMBER` of seconds).</BR></BR> **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read``` (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
Status Code Description Response Headers
200 ok response -
429 over limit -
*/ public Object publicAuthGet(String grantType, String username, String password, String clientId, String clientSecret, String refreshToken, String timestamp, String signature, String nonce, String state, String scope) throws ApiException { ApiResponse localVarResp = publicAuthGetWithHttpInfo(grantType, username, password, clientId, clientSecret, refreshToken, timestamp, signature, nonce, state, scope); @@ -230,6 +242,12 @@ public Object publicAuthGet(String grantType, String username, String password, * @param scope Describes type of the access for assigned token, possible values: `connection`, `session`, `session:name`, `trade:[read, read_write, none]`, `wallet:[read, read_write, none]`, `account:[read, read_write, none]`, `expires:NUMBER` (token will expire after `NUMBER` of seconds).</BR></BR> **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read``` (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
Status Code Description Response Headers
200 ok response -
429 over limit -
*/ public ApiResponse publicAuthGetWithHttpInfo(String grantType, String username, String password, String clientId, String clientSecret, String refreshToken, String timestamp, String signature, String nonce, String state, String scope) throws ApiException { okhttp3.Call localVarCall = publicAuthGetValidateBeforeCall(grantType, username, password, clientId, clientSecret, refreshToken, timestamp, signature, nonce, state, scope, null); @@ -254,6 +272,12 @@ public ApiResponse publicAuthGetWithHttpInfo(String grantType, String us * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + +
Status Code Description Response Headers
200 ok response -
429 over limit -
*/ public okhttp3.Call publicAuthGetAsync(String grantType, String username, String password, String clientId, String clientSecret, String refreshToken, String timestamp, String signature, String nonce, String state, String scope, final ApiCallback _callback) throws ApiException { @@ -267,6 +291,11 @@ public okhttp3.Call publicAuthGetAsync(String grantType, String username, String * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetAnnouncementsGetCall(final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -310,6 +339,11 @@ private okhttp3.Call publicGetAnnouncementsGetValidateBeforeCall(final ApiCallba * * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetAnnouncementsGet() throws ApiException { ApiResponse localVarResp = publicGetAnnouncementsGetWithHttpInfo(); @@ -321,6 +355,11 @@ public Object publicGetAnnouncementsGet() throws ApiException { * * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetAnnouncementsGetWithHttpInfo() throws ApiException { okhttp3.Call localVarCall = publicGetAnnouncementsGetValidateBeforeCall(null); @@ -334,6 +373,11 @@ public ApiResponse publicGetAnnouncementsGetWithHttpInfo() throws ApiExc * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetAnnouncementsGetAsync(final ApiCallback _callback) throws ApiException { @@ -349,6 +393,11 @@ public okhttp3.Call publicGetAnnouncementsGetAsync(final ApiCallback _ca * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetBookSummaryByCurrencyGetCall(String currency, String kind, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -407,6 +456,11 @@ private okhttp3.Call publicGetBookSummaryByCurrencyGetValidateBeforeCall(String * @param kind Instrument kind, if not provided instruments of all kinds are considered (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetBookSummaryByCurrencyGet(String currency, String kind) throws ApiException { ApiResponse localVarResp = publicGetBookSummaryByCurrencyGetWithHttpInfo(currency, kind); @@ -420,6 +474,11 @@ public Object publicGetBookSummaryByCurrencyGet(String currency, String kind) th * @param kind Instrument kind, if not provided instruments of all kinds are considered (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetBookSummaryByCurrencyGetWithHttpInfo(String currency, String kind) throws ApiException { okhttp3.Call localVarCall = publicGetBookSummaryByCurrencyGetValidateBeforeCall(currency, kind, null); @@ -435,6 +494,11 @@ public ApiResponse publicGetBookSummaryByCurrencyGetWithHttpInfo(String * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetBookSummaryByCurrencyGetAsync(String currency, String kind, final ApiCallback _callback) throws ApiException { @@ -449,6 +513,11 @@ public okhttp3.Call publicGetBookSummaryByCurrencyGetAsync(String currency, Stri * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetBookSummaryByInstrumentGetCall(String instrumentName, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -502,6 +571,11 @@ private okhttp3.Call publicGetBookSummaryByInstrumentGetValidateBeforeCall(Strin * @param instrumentName Instrument name (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetBookSummaryByInstrumentGet(String instrumentName) throws ApiException { ApiResponse localVarResp = publicGetBookSummaryByInstrumentGetWithHttpInfo(instrumentName); @@ -514,6 +588,11 @@ public Object publicGetBookSummaryByInstrumentGet(String instrumentName) throws * @param instrumentName Instrument name (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetBookSummaryByInstrumentGetWithHttpInfo(String instrumentName) throws ApiException { okhttp3.Call localVarCall = publicGetBookSummaryByInstrumentGetValidateBeforeCall(instrumentName, null); @@ -528,6 +607,11 @@ public ApiResponse publicGetBookSummaryByInstrumentGetWithHttpInfo(Strin * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetBookSummaryByInstrumentGetAsync(String instrumentName, final ApiCallback _callback) throws ApiException { @@ -542,6 +626,11 @@ public okhttp3.Call publicGetBookSummaryByInstrumentGetAsync(String instrumentNa * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call publicGetContractSizeGetCall(String instrumentName, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -595,6 +684,11 @@ private okhttp3.Call publicGetContractSizeGetValidateBeforeCall(String instrumen * @param instrumentName Instrument name (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object publicGetContractSizeGet(String instrumentName) throws ApiException { ApiResponse localVarResp = publicGetContractSizeGetWithHttpInfo(instrumentName); @@ -607,6 +701,11 @@ public Object publicGetContractSizeGet(String instrumentName) throws ApiExceptio * @param instrumentName Instrument name (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse publicGetContractSizeGetWithHttpInfo(String instrumentName) throws ApiException { okhttp3.Call localVarCall = publicGetContractSizeGetValidateBeforeCall(instrumentName, null); @@ -621,6 +720,11 @@ public ApiResponse publicGetContractSizeGetWithHttpInfo(String instrumen * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call publicGetContractSizeGetAsync(String instrumentName, final ApiCallback _callback) throws ApiException { @@ -634,6 +738,11 @@ public okhttp3.Call publicGetContractSizeGetAsync(String instrumentName, final A * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call publicGetCurrenciesGetCall(final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -677,6 +786,11 @@ private okhttp3.Call publicGetCurrenciesGetValidateBeforeCall(final ApiCallback * * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object publicGetCurrenciesGet() throws ApiException { ApiResponse localVarResp = publicGetCurrenciesGetWithHttpInfo(); @@ -688,6 +802,11 @@ public Object publicGetCurrenciesGet() throws ApiException { * * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse publicGetCurrenciesGetWithHttpInfo() throws ApiException { okhttp3.Call localVarCall = publicGetCurrenciesGetValidateBeforeCall(null); @@ -701,6 +820,11 @@ public ApiResponse publicGetCurrenciesGetWithHttpInfo() throws ApiExcept * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call publicGetCurrenciesGetAsync(final ApiCallback _callback) throws ApiException { @@ -716,6 +840,11 @@ public okhttp3.Call publicGetCurrenciesGetAsync(final ApiCallback _callb * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetFundingChartDataGetCall(String instrumentName, String length, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -774,6 +903,11 @@ private okhttp3.Call publicGetFundingChartDataGetValidateBeforeCall(String instr * @param length Specifies time period. `8h` - 8 hours, `24h` - 24 hours (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetFundingChartDataGet(String instrumentName, String length) throws ApiException { ApiResponse localVarResp = publicGetFundingChartDataGetWithHttpInfo(instrumentName, length); @@ -787,6 +921,11 @@ public Object publicGetFundingChartDataGet(String instrumentName, String length) * @param length Specifies time period. `8h` - 8 hours, `24h` - 24 hours (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetFundingChartDataGetWithHttpInfo(String instrumentName, String length) throws ApiException { okhttp3.Call localVarCall = publicGetFundingChartDataGetValidateBeforeCall(instrumentName, length, null); @@ -802,6 +941,11 @@ public ApiResponse publicGetFundingChartDataGetWithHttpInfo(String instr * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetFundingChartDataGetAsync(String instrumentName, String length, final ApiCallback _callback) throws ApiException { @@ -816,6 +960,11 @@ public okhttp3.Call publicGetFundingChartDataGetAsync(String instrumentName, Str * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call publicGetHistoricalVolatilityGetCall(String currency, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -869,6 +1018,11 @@ private okhttp3.Call publicGetHistoricalVolatilityGetValidateBeforeCall(String c * @param currency The currency symbol (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object publicGetHistoricalVolatilityGet(String currency) throws ApiException { ApiResponse localVarResp = publicGetHistoricalVolatilityGetWithHttpInfo(currency); @@ -881,6 +1035,11 @@ public Object publicGetHistoricalVolatilityGet(String currency) throws ApiExcept * @param currency The currency symbol (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse publicGetHistoricalVolatilityGetWithHttpInfo(String currency) throws ApiException { okhttp3.Call localVarCall = publicGetHistoricalVolatilityGetValidateBeforeCall(currency, null); @@ -895,6 +1054,11 @@ public ApiResponse publicGetHistoricalVolatilityGetWithHttpInfo(String c * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call publicGetHistoricalVolatilityGetAsync(String currency, final ApiCallback _callback) throws ApiException { @@ -909,6 +1073,11 @@ public okhttp3.Call publicGetHistoricalVolatilityGetAsync(String currency, final * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetIndexGetCall(String currency, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -962,6 +1131,11 @@ private okhttp3.Call publicGetIndexGetValidateBeforeCall(String currency, final * @param currency The currency symbol (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetIndexGet(String currency) throws ApiException { ApiResponse localVarResp = publicGetIndexGetWithHttpInfo(currency); @@ -974,6 +1148,11 @@ public Object publicGetIndexGet(String currency) throws ApiException { * @param currency The currency symbol (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetIndexGetWithHttpInfo(String currency) throws ApiException { okhttp3.Call localVarCall = publicGetIndexGetValidateBeforeCall(currency, null); @@ -988,6 +1167,11 @@ public ApiResponse publicGetIndexGetWithHttpInfo(String currency) throws * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetIndexGetAsync(String currency, final ApiCallback _callback) throws ApiException { @@ -1004,6 +1188,11 @@ public okhttp3.Call publicGetIndexGetAsync(String currency, final ApiCallback + Status Code Description Response Headers + 200 ok response - + */ public okhttp3.Call publicGetInstrumentsGetCall(String currency, String kind, Boolean expired, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1067,6 +1256,11 @@ private okhttp3.Call publicGetInstrumentsGetValidateBeforeCall(String currency, * @param expired Set to true to show expired instruments instead of active ones. (optional, default to false) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object publicGetInstrumentsGet(String currency, String kind, Boolean expired) throws ApiException { ApiResponse localVarResp = publicGetInstrumentsGetWithHttpInfo(currency, kind, expired); @@ -1081,6 +1275,11 @@ public Object publicGetInstrumentsGet(String currency, String kind, Boolean expi * @param expired Set to true to show expired instruments instead of active ones. (optional, default to false) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse publicGetInstrumentsGetWithHttpInfo(String currency, String kind, Boolean expired) throws ApiException { okhttp3.Call localVarCall = publicGetInstrumentsGetValidateBeforeCall(currency, kind, expired, null); @@ -1097,6 +1296,11 @@ public ApiResponse publicGetInstrumentsGetWithHttpInfo(String currency, * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call publicGetInstrumentsGetAsync(String currency, String kind, Boolean expired, final ApiCallback _callback) throws ApiException { @@ -1115,6 +1319,11 @@ public okhttp3.Call publicGetInstrumentsGetAsync(String currency, String kind, B * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetLastSettlementsByCurrencyGetCall(String currency, String type, Integer count, String continuation, Integer searchStartTimestamp, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1188,6 +1397,11 @@ private okhttp3.Call publicGetLastSettlementsByCurrencyGetValidateBeforeCall(Str * @param searchStartTimestamp The latest timestamp to return result for (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetLastSettlementsByCurrencyGet(String currency, String type, Integer count, String continuation, Integer searchStartTimestamp) throws ApiException { ApiResponse localVarResp = publicGetLastSettlementsByCurrencyGetWithHttpInfo(currency, type, count, continuation, searchStartTimestamp); @@ -1204,6 +1418,11 @@ public Object publicGetLastSettlementsByCurrencyGet(String currency, String type * @param searchStartTimestamp The latest timestamp to return result for (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetLastSettlementsByCurrencyGetWithHttpInfo(String currency, String type, Integer count, String continuation, Integer searchStartTimestamp) throws ApiException { okhttp3.Call localVarCall = publicGetLastSettlementsByCurrencyGetValidateBeforeCall(currency, type, count, continuation, searchStartTimestamp, null); @@ -1222,6 +1441,11 @@ public ApiResponse publicGetLastSettlementsByCurrencyGetWithHttpInfo(Str * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetLastSettlementsByCurrencyGetAsync(String currency, String type, Integer count, String continuation, Integer searchStartTimestamp, final ApiCallback _callback) throws ApiException { @@ -1240,6 +1464,11 @@ public okhttp3.Call publicGetLastSettlementsByCurrencyGetAsync(String currency, * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetLastSettlementsByInstrumentGetCall(String instrumentName, String type, Integer count, String continuation, Integer searchStartTimestamp, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1313,6 +1542,11 @@ private okhttp3.Call publicGetLastSettlementsByInstrumentGetValidateBeforeCall(S * @param searchStartTimestamp The latest timestamp to return result for (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetLastSettlementsByInstrumentGet(String instrumentName, String type, Integer count, String continuation, Integer searchStartTimestamp) throws ApiException { ApiResponse localVarResp = publicGetLastSettlementsByInstrumentGetWithHttpInfo(instrumentName, type, count, continuation, searchStartTimestamp); @@ -1329,6 +1563,11 @@ public Object publicGetLastSettlementsByInstrumentGet(String instrumentName, Str * @param searchStartTimestamp The latest timestamp to return result for (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetLastSettlementsByInstrumentGetWithHttpInfo(String instrumentName, String type, Integer count, String continuation, Integer searchStartTimestamp) throws ApiException { okhttp3.Call localVarCall = publicGetLastSettlementsByInstrumentGetValidateBeforeCall(instrumentName, type, count, continuation, searchStartTimestamp, null); @@ -1347,6 +1586,11 @@ public ApiResponse publicGetLastSettlementsByInstrumentGetWithHttpInfo(S * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetLastSettlementsByInstrumentGetAsync(String instrumentName, String type, Integer count, String continuation, Integer searchStartTimestamp, final ApiCallback _callback) throws ApiException { @@ -1367,6 +1611,11 @@ public okhttp3.Call publicGetLastSettlementsByInstrumentGetAsync(String instrume * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetLastTradesByCurrencyAndTimeGetCall(String currency, Integer startTimestamp, Integer endTimestamp, String kind, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1460,6 +1709,11 @@ private okhttp3.Call publicGetLastTradesByCurrencyAndTimeGetValidateBeforeCall(S * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetLastTradesByCurrencyAndTimeGet(String currency, Integer startTimestamp, Integer endTimestamp, String kind, Integer count, Boolean includeOld, String sorting) throws ApiException { ApiResponse localVarResp = publicGetLastTradesByCurrencyAndTimeGetWithHttpInfo(currency, startTimestamp, endTimestamp, kind, count, includeOld, sorting); @@ -1478,6 +1732,11 @@ public Object publicGetLastTradesByCurrencyAndTimeGet(String currency, Integer s * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetLastTradesByCurrencyAndTimeGetWithHttpInfo(String currency, Integer startTimestamp, Integer endTimestamp, String kind, Integer count, Boolean includeOld, String sorting) throws ApiException { okhttp3.Call localVarCall = publicGetLastTradesByCurrencyAndTimeGetValidateBeforeCall(currency, startTimestamp, endTimestamp, kind, count, includeOld, sorting, null); @@ -1498,6 +1757,11 @@ public ApiResponse publicGetLastTradesByCurrencyAndTimeGetWithHttpInfo(S * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetLastTradesByCurrencyAndTimeGetAsync(String currency, Integer startTimestamp, Integer endTimestamp, String kind, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { @@ -1518,6 +1782,11 @@ public okhttp3.Call publicGetLastTradesByCurrencyAndTimeGetAsync(String currency * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetLastTradesByCurrencyGetCall(String currency, String kind, String startId, String endId, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1601,6 +1870,11 @@ private okhttp3.Call publicGetLastTradesByCurrencyGetValidateBeforeCall(String c * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetLastTradesByCurrencyGet(String currency, String kind, String startId, String endId, Integer count, Boolean includeOld, String sorting) throws ApiException { ApiResponse localVarResp = publicGetLastTradesByCurrencyGetWithHttpInfo(currency, kind, startId, endId, count, includeOld, sorting); @@ -1619,6 +1893,11 @@ public Object publicGetLastTradesByCurrencyGet(String currency, String kind, Str * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetLastTradesByCurrencyGetWithHttpInfo(String currency, String kind, String startId, String endId, Integer count, Boolean includeOld, String sorting) throws ApiException { okhttp3.Call localVarCall = publicGetLastTradesByCurrencyGetValidateBeforeCall(currency, kind, startId, endId, count, includeOld, sorting, null); @@ -1639,6 +1918,11 @@ public ApiResponse publicGetLastTradesByCurrencyGetWithHttpInfo(String c * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetLastTradesByCurrencyGetAsync(String currency, String kind, String startId, String endId, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { @@ -1658,6 +1942,11 @@ public okhttp3.Call publicGetLastTradesByCurrencyGetAsync(String currency, Strin * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetLastTradesByInstrumentAndTimeGetCall(String instrumentName, Integer startTimestamp, Integer endTimestamp, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1746,6 +2035,11 @@ private okhttp3.Call publicGetLastTradesByInstrumentAndTimeGetValidateBeforeCall * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetLastTradesByInstrumentAndTimeGet(String instrumentName, Integer startTimestamp, Integer endTimestamp, Integer count, Boolean includeOld, String sorting) throws ApiException { ApiResponse localVarResp = publicGetLastTradesByInstrumentAndTimeGetWithHttpInfo(instrumentName, startTimestamp, endTimestamp, count, includeOld, sorting); @@ -1763,6 +2057,11 @@ public Object publicGetLastTradesByInstrumentAndTimeGet(String instrumentName, I * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetLastTradesByInstrumentAndTimeGetWithHttpInfo(String instrumentName, Integer startTimestamp, Integer endTimestamp, Integer count, Boolean includeOld, String sorting) throws ApiException { okhttp3.Call localVarCall = publicGetLastTradesByInstrumentAndTimeGetValidateBeforeCall(instrumentName, startTimestamp, endTimestamp, count, includeOld, sorting, null); @@ -1782,6 +2081,11 @@ public ApiResponse publicGetLastTradesByInstrumentAndTimeGetWithHttpInfo * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetLastTradesByInstrumentAndTimeGetAsync(String instrumentName, Integer startTimestamp, Integer endTimestamp, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { @@ -1801,6 +2105,11 @@ public okhttp3.Call publicGetLastTradesByInstrumentAndTimeGetAsync(String instru * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetLastTradesByInstrumentGetCall(String instrumentName, Integer startSeq, Integer endSeq, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1879,6 +2188,11 @@ private okhttp3.Call publicGetLastTradesByInstrumentGetValidateBeforeCall(String * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetLastTradesByInstrumentGet(String instrumentName, Integer startSeq, Integer endSeq, Integer count, Boolean includeOld, String sorting) throws ApiException { ApiResponse localVarResp = publicGetLastTradesByInstrumentGetWithHttpInfo(instrumentName, startSeq, endSeq, count, includeOld, sorting); @@ -1896,6 +2210,11 @@ public Object publicGetLastTradesByInstrumentGet(String instrumentName, Integer * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetLastTradesByInstrumentGetWithHttpInfo(String instrumentName, Integer startSeq, Integer endSeq, Integer count, Boolean includeOld, String sorting) throws ApiException { okhttp3.Call localVarCall = publicGetLastTradesByInstrumentGetValidateBeforeCall(instrumentName, startSeq, endSeq, count, includeOld, sorting, null); @@ -1915,6 +2234,11 @@ public ApiResponse publicGetLastTradesByInstrumentGetWithHttpInfo(String * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetLastTradesByInstrumentGetAsync(String instrumentName, Integer startSeq, Integer endSeq, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { @@ -1930,6 +2254,11 @@ public okhttp3.Call publicGetLastTradesByInstrumentGetAsync(String instrumentNam * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetOrderBookGetCall(String instrumentName, BigDecimal depth, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1988,6 +2317,11 @@ private okhttp3.Call publicGetOrderBookGetValidateBeforeCall(String instrumentNa * @param depth The number of entries to return for bids and asks. (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetOrderBookGet(String instrumentName, BigDecimal depth) throws ApiException { ApiResponse localVarResp = publicGetOrderBookGetWithHttpInfo(instrumentName, depth); @@ -2001,6 +2335,11 @@ public Object publicGetOrderBookGet(String instrumentName, BigDecimal depth) thr * @param depth The number of entries to return for bids and asks. (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetOrderBookGetWithHttpInfo(String instrumentName, BigDecimal depth) throws ApiException { okhttp3.Call localVarCall = publicGetOrderBookGetValidateBeforeCall(instrumentName, depth, null); @@ -2016,6 +2355,11 @@ public ApiResponse publicGetOrderBookGetWithHttpInfo(String instrumentNa * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetOrderBookGetAsync(String instrumentName, BigDecimal depth, final ApiCallback _callback) throws ApiException { @@ -2029,6 +2373,11 @@ public okhttp3.Call publicGetOrderBookGetAsync(String instrumentName, BigDecimal * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetTimeGetCall(final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -2072,6 +2421,11 @@ private okhttp3.Call publicGetTimeGetValidateBeforeCall(final ApiCallback _callb * * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetTimeGet() throws ApiException { ApiResponse localVarResp = publicGetTimeGetWithHttpInfo(); @@ -2083,6 +2437,11 @@ public Object publicGetTimeGet() throws ApiException { * * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetTimeGetWithHttpInfo() throws ApiException { okhttp3.Call localVarCall = publicGetTimeGetValidateBeforeCall(null); @@ -2096,6 +2455,11 @@ public ApiResponse publicGetTimeGetWithHttpInfo() throws ApiException { * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetTimeGetAsync(final ApiCallback _callback) throws ApiException { @@ -2109,6 +2473,11 @@ public okhttp3.Call publicGetTimeGetAsync(final ApiCallback _callback) t * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetTradeVolumesGetCall(final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -2152,6 +2521,11 @@ private okhttp3.Call publicGetTradeVolumesGetValidateBeforeCall(final ApiCallbac * * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetTradeVolumesGet() throws ApiException { ApiResponse localVarResp = publicGetTradeVolumesGetWithHttpInfo(); @@ -2163,6 +2537,11 @@ public Object publicGetTradeVolumesGet() throws ApiException { * * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetTradeVolumesGetWithHttpInfo() throws ApiException { okhttp3.Call localVarCall = publicGetTradeVolumesGetValidateBeforeCall(null); @@ -2176,6 +2555,11 @@ public ApiResponse publicGetTradeVolumesGetWithHttpInfo() throws ApiExce * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetTradeVolumesGetAsync(final ApiCallback _callback) throws ApiException { @@ -2192,6 +2576,11 @@ public okhttp3.Call publicGetTradeVolumesGetAsync(final ApiCallback _cal * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetTradingviewChartDataGetCall(String instrumentName, Integer startTimestamp, Integer endTimestamp, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -2265,6 +2654,11 @@ private okhttp3.Call publicGetTradingviewChartDataGetValidateBeforeCall(String i * @param endTimestamp The most recent timestamp to return result for (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetTradingviewChartDataGet(String instrumentName, Integer startTimestamp, Integer endTimestamp) throws ApiException { ApiResponse localVarResp = publicGetTradingviewChartDataGetWithHttpInfo(instrumentName, startTimestamp, endTimestamp); @@ -2279,6 +2673,11 @@ public Object publicGetTradingviewChartDataGet(String instrumentName, Integer st * @param endTimestamp The most recent timestamp to return result for (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetTradingviewChartDataGetWithHttpInfo(String instrumentName, Integer startTimestamp, Integer endTimestamp) throws ApiException { okhttp3.Call localVarCall = publicGetTradingviewChartDataGetValidateBeforeCall(instrumentName, startTimestamp, endTimestamp, null); @@ -2295,6 +2694,11 @@ public ApiResponse publicGetTradingviewChartDataGetWithHttpInfo(String i * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetTradingviewChartDataGetAsync(String instrumentName, Integer startTimestamp, Integer endTimestamp, final ApiCallback _callback) throws ApiException { @@ -2309,6 +2713,11 @@ public okhttp3.Call publicGetTradingviewChartDataGetAsync(String instrumentName, * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicTestGetCall(String expectedResult, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -2357,6 +2766,11 @@ private okhttp3.Call publicTestGetValidateBeforeCall(String expectedResult, fina * @param expectedResult The value \"exception\" will trigger an error response. This may be useful for testing wrapper libraries. (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicTestGet(String expectedResult) throws ApiException { ApiResponse localVarResp = publicTestGetWithHttpInfo(expectedResult); @@ -2369,6 +2783,11 @@ public Object publicTestGet(String expectedResult) throws ApiException { * @param expectedResult The value \"exception\" will trigger an error response. This may be useful for testing wrapper libraries. (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicTestGetWithHttpInfo(String expectedResult) throws ApiException { okhttp3.Call localVarCall = publicTestGetValidateBeforeCall(expectedResult, null); @@ -2383,6 +2802,11 @@ public ApiResponse publicTestGetWithHttpInfo(String expectedResult) thro * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicTestGetAsync(String expectedResult, final ApiCallback _callback) throws ApiException { @@ -2397,6 +2821,11 @@ public okhttp3.Call publicTestGetAsync(String expectedResult, final ApiCallback< * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call publicTickerGetCall(String instrumentName, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -2450,6 +2879,11 @@ private okhttp3.Call publicTickerGetValidateBeforeCall(String instrumentName, fi * @param instrumentName Instrument name (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object publicTickerGet(String instrumentName) throws ApiException { ApiResponse localVarResp = publicTickerGetWithHttpInfo(instrumentName); @@ -2462,6 +2896,11 @@ public Object publicTickerGet(String instrumentName) throws ApiException { * @param instrumentName Instrument name (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse publicTickerGetWithHttpInfo(String instrumentName) throws ApiException { okhttp3.Call localVarCall = publicTickerGetValidateBeforeCall(instrumentName, null); @@ -2476,6 +2915,11 @@ public ApiResponse publicTickerGetWithHttpInfo(String instrumentName) th * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call publicTickerGetAsync(String instrumentName, final ApiCallback _callback) throws ApiException { @@ -2492,6 +2936,11 @@ public okhttp3.Call publicTickerGetAsync(String instrumentName, final ApiCallbac * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicValidateFieldGetCall(String field, String value, String value2, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -2560,6 +3009,11 @@ private okhttp3.Call publicValidateFieldGetValidateBeforeCall(String field, Stri * @param value2 Additional value to be compared with (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicValidateFieldGet(String field, String value, String value2) throws ApiException { ApiResponse localVarResp = publicValidateFieldGetWithHttpInfo(field, value, value2); @@ -2574,6 +3028,11 @@ public Object publicValidateFieldGet(String field, String value, String value2) * @param value2 Additional value to be compared with (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicValidateFieldGetWithHttpInfo(String field, String value, String value2) throws ApiException { okhttp3.Call localVarCall = publicValidateFieldGetValidateBeforeCall(field, value, value2, null); @@ -2590,6 +3049,11 @@ public ApiResponse publicValidateFieldGetWithHttpInfo(String field, Stri * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicValidateFieldGetAsync(String field, String value, String value2, final ApiCallback _callback) throws ApiException { diff --git a/java/src/main/java/org/openapitools/client/api/SupportingApi.java b/java/src/main/java/org/openapitools/client/api/SupportingApi.java index ee09241..a891508 100644 --- a/java/src/main/java/org/openapitools/client/api/SupportingApi.java +++ b/java/src/main/java/org/openapitools/client/api/SupportingApi.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -58,6 +58,11 @@ public void setApiClient(ApiClient apiClient) { * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetTimeGetCall(final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -101,6 +106,11 @@ private okhttp3.Call publicGetTimeGetValidateBeforeCall(final ApiCallback _callb * * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicGetTimeGet() throws ApiException { ApiResponse localVarResp = publicGetTimeGetWithHttpInfo(); @@ -112,6 +122,11 @@ public Object publicGetTimeGet() throws ApiException { * * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicGetTimeGetWithHttpInfo() throws ApiException { okhttp3.Call localVarCall = publicGetTimeGetValidateBeforeCall(null); @@ -125,6 +140,11 @@ public ApiResponse publicGetTimeGetWithHttpInfo() throws ApiException { * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicGetTimeGetAsync(final ApiCallback _callback) throws ApiException { @@ -139,6 +159,11 @@ public okhttp3.Call publicGetTimeGetAsync(final ApiCallback _callback) t * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicTestGetCall(String expectedResult, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -187,6 +212,11 @@ private okhttp3.Call publicTestGetValidateBeforeCall(String expectedResult, fina * @param expectedResult The value \"exception\" will trigger an error response. This may be useful for testing wrapper libraries. (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object publicTestGet(String expectedResult) throws ApiException { ApiResponse localVarResp = publicTestGetWithHttpInfo(expectedResult); @@ -199,6 +229,11 @@ public Object publicTestGet(String expectedResult) throws ApiException { * @param expectedResult The value \"exception\" will trigger an error response. This may be useful for testing wrapper libraries. (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse publicTestGetWithHttpInfo(String expectedResult) throws ApiException { okhttp3.Call localVarCall = publicTestGetValidateBeforeCall(expectedResult, null); @@ -213,6 +248,11 @@ public ApiResponse publicTestGetWithHttpInfo(String expectedResult) thro * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call publicTestGetAsync(String expectedResult, final ApiCallback _callback) throws ApiException { diff --git a/java/src/main/java/org/openapitools/client/api/TradingApi.java b/java/src/main/java/org/openapitools/client/api/TradingApi.java index 8b0f18a..ca78679 100644 --- a/java/src/main/java/org/openapitools/client/api/TradingApi.java +++ b/java/src/main/java/org/openapitools/client/api/TradingApi.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -71,6 +71,11 @@ public void setApiClient(ApiClient apiClient) { * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateBuyGetCall(String instrumentName, BigDecimal amount, String type, String label, BigDecimal price, String timeInForce, BigDecimal maxShow, Boolean postOnly, Boolean reduceOnly, BigDecimal stopPrice, String trigger, String advanced, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -184,6 +189,11 @@ private okhttp3.Call privateBuyGetValidateBeforeCall(String instrumentName, BigD * @param advanced Advanced option order type. (Only for options) (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateBuyGet(String instrumentName, BigDecimal amount, String type, String label, BigDecimal price, String timeInForce, BigDecimal maxShow, Boolean postOnly, Boolean reduceOnly, BigDecimal stopPrice, String trigger, String advanced) throws ApiException { ApiResponse localVarResp = privateBuyGetWithHttpInfo(instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced); @@ -207,6 +217,11 @@ public Object privateBuyGet(String instrumentName, BigDecimal amount, String typ * @param advanced Advanced option order type. (Only for options) (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateBuyGetWithHttpInfo(String instrumentName, BigDecimal amount, String type, String label, BigDecimal price, String timeInForce, BigDecimal maxShow, Boolean postOnly, Boolean reduceOnly, BigDecimal stopPrice, String trigger, String advanced) throws ApiException { okhttp3.Call localVarCall = privateBuyGetValidateBeforeCall(instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced, null); @@ -232,6 +247,11 @@ public ApiResponse privateBuyGetWithHttpInfo(String instrumentName, BigD * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateBuyGetAsync(String instrumentName, BigDecimal amount, String type, String label, BigDecimal price, String timeInForce, BigDecimal maxShow, Boolean postOnly, Boolean reduceOnly, BigDecimal stopPrice, String trigger, String advanced, final ApiCallback _callback) throws ApiException { @@ -248,6 +268,11 @@ public okhttp3.Call privateBuyGetAsync(String instrumentName, BigDecimal amount, * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateCancelAllByCurrencyGetCall(String currency, String kind, String type, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -311,6 +336,11 @@ private okhttp3.Call privateCancelAllByCurrencyGetValidateBeforeCall(String curr * @param type Order type - limit, stop or all, default - `all` (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateCancelAllByCurrencyGet(String currency, String kind, String type) throws ApiException { ApiResponse localVarResp = privateCancelAllByCurrencyGetWithHttpInfo(currency, kind, type); @@ -325,6 +355,11 @@ public Object privateCancelAllByCurrencyGet(String currency, String kind, String * @param type Order type - limit, stop or all, default - `all` (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateCancelAllByCurrencyGetWithHttpInfo(String currency, String kind, String type) throws ApiException { okhttp3.Call localVarCall = privateCancelAllByCurrencyGetValidateBeforeCall(currency, kind, type, null); @@ -341,6 +376,11 @@ public ApiResponse privateCancelAllByCurrencyGetWithHttpInfo(String curr * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateCancelAllByCurrencyGetAsync(String currency, String kind, String type, final ApiCallback _callback) throws ApiException { @@ -356,6 +396,11 @@ public okhttp3.Call privateCancelAllByCurrencyGetAsync(String currency, String k * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateCancelAllByInstrumentGetCall(String instrumentName, String type, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -414,6 +459,11 @@ private okhttp3.Call privateCancelAllByInstrumentGetValidateBeforeCall(String in * @param type Order type - limit, stop or all, default - `all` (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateCancelAllByInstrumentGet(String instrumentName, String type) throws ApiException { ApiResponse localVarResp = privateCancelAllByInstrumentGetWithHttpInfo(instrumentName, type); @@ -427,6 +477,11 @@ public Object privateCancelAllByInstrumentGet(String instrumentName, String type * @param type Order type - limit, stop or all, default - `all` (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateCancelAllByInstrumentGetWithHttpInfo(String instrumentName, String type) throws ApiException { okhttp3.Call localVarCall = privateCancelAllByInstrumentGetValidateBeforeCall(instrumentName, type, null); @@ -442,6 +497,11 @@ public ApiResponse privateCancelAllByInstrumentGetWithHttpInfo(String in * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateCancelAllByInstrumentGetAsync(String instrumentName, String type, final ApiCallback _callback) throws ApiException { @@ -455,6 +515,11 @@ public okhttp3.Call privateCancelAllByInstrumentGetAsync(String instrumentName, * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateCancelAllGetCall(final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -498,6 +563,11 @@ private okhttp3.Call privateCancelAllGetValidateBeforeCall(final ApiCallback _ca * * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateCancelAllGet() throws ApiException { ApiResponse localVarResp = privateCancelAllGetWithHttpInfo(); @@ -509,6 +579,11 @@ public Object privateCancelAllGet() throws ApiException { * * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateCancelAllGetWithHttpInfo() throws ApiException { okhttp3.Call localVarCall = privateCancelAllGetValidateBeforeCall(null); @@ -522,6 +597,11 @@ public ApiResponse privateCancelAllGetWithHttpInfo() throws ApiException * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateCancelAllGetAsync(final ApiCallback _callback) throws ApiException { @@ -536,6 +616,11 @@ public okhttp3.Call privateCancelAllGetAsync(final ApiCallback _callback * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateCancelGetCall(String orderId, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -589,6 +674,11 @@ private okhttp3.Call privateCancelGetValidateBeforeCall(String orderId, final Ap * @param orderId The order id (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateCancelGet(String orderId) throws ApiException { ApiResponse localVarResp = privateCancelGetWithHttpInfo(orderId); @@ -601,6 +691,11 @@ public Object privateCancelGet(String orderId) throws ApiException { * @param orderId The order id (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateCancelGetWithHttpInfo(String orderId) throws ApiException { okhttp3.Call localVarCall = privateCancelGetValidateBeforeCall(orderId, null); @@ -615,6 +710,11 @@ public ApiResponse privateCancelGetWithHttpInfo(String orderId) throws A * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateCancelGetAsync(String orderId, final ApiCallback _callback) throws ApiException { @@ -631,6 +731,11 @@ public okhttp3.Call privateCancelGetAsync(String orderId, final ApiCallback + Status Code Description Response Headers + 200 ok response - + */ public okhttp3.Call privateClosePositionGetCall(String instrumentName, String type, BigDecimal price, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -699,6 +804,11 @@ private okhttp3.Call privateClosePositionGetValidateBeforeCall(String instrument * @param price Optional price for limit order. (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateClosePositionGet(String instrumentName, String type, BigDecimal price) throws ApiException { ApiResponse localVarResp = privateClosePositionGetWithHttpInfo(instrumentName, type, price); @@ -713,6 +823,11 @@ public Object privateClosePositionGet(String instrumentName, String type, BigDec * @param price Optional price for limit order. (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateClosePositionGetWithHttpInfo(String instrumentName, String type, BigDecimal price) throws ApiException { okhttp3.Call localVarCall = privateClosePositionGetValidateBeforeCall(instrumentName, type, price, null); @@ -729,6 +844,11 @@ public ApiResponse privateClosePositionGetWithHttpInfo(String instrument * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateClosePositionGetAsync(String instrumentName, String type, BigDecimal price, final ApiCallback _callback) throws ApiException { @@ -748,6 +868,11 @@ public okhttp3.Call privateClosePositionGetAsync(String instrumentName, String t * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateEditGetCall(String orderId, BigDecimal amount, BigDecimal price, Boolean postOnly, String advanced, BigDecimal stopPrice, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -836,6 +961,11 @@ private okhttp3.Call privateEditGetValidateBeforeCall(String orderId, BigDecimal * @param stopPrice Stop price, required for stop limit orders (Only for stop orders) (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateEditGet(String orderId, BigDecimal amount, BigDecimal price, Boolean postOnly, String advanced, BigDecimal stopPrice) throws ApiException { ApiResponse localVarResp = privateEditGetWithHttpInfo(orderId, amount, price, postOnly, advanced, stopPrice); @@ -853,6 +983,11 @@ public Object privateEditGet(String orderId, BigDecimal amount, BigDecimal price * @param stopPrice Stop price, required for stop limit orders (Only for stop orders) (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateEditGetWithHttpInfo(String orderId, BigDecimal amount, BigDecimal price, Boolean postOnly, String advanced, BigDecimal stopPrice) throws ApiException { okhttp3.Call localVarCall = privateEditGetValidateBeforeCall(orderId, amount, price, postOnly, advanced, stopPrice, null); @@ -872,6 +1007,11 @@ public ApiResponse privateEditGetWithHttpInfo(String orderId, BigDecimal * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateEditGetAsync(String orderId, BigDecimal amount, BigDecimal price, Boolean postOnly, String advanced, BigDecimal stopPrice, final ApiCallback _callback) throws ApiException { @@ -888,6 +1028,11 @@ public okhttp3.Call privateEditGetAsync(String orderId, BigDecimal amount, BigDe * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetMarginsGetCall(String instrumentName, BigDecimal amount, BigDecimal price, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -961,6 +1106,11 @@ private okhttp3.Call privateGetMarginsGetValidateBeforeCall(String instrumentNam * @param price Price (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetMarginsGet(String instrumentName, BigDecimal amount, BigDecimal price) throws ApiException { ApiResponse localVarResp = privateGetMarginsGetWithHttpInfo(instrumentName, amount, price); @@ -975,6 +1125,11 @@ public Object privateGetMarginsGet(String instrumentName, BigDecimal amount, Big * @param price Price (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetMarginsGetWithHttpInfo(String instrumentName, BigDecimal amount, BigDecimal price) throws ApiException { okhttp3.Call localVarCall = privateGetMarginsGetValidateBeforeCall(instrumentName, amount, price, null); @@ -991,6 +1146,11 @@ public ApiResponse privateGetMarginsGetWithHttpInfo(String instrumentNam * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetMarginsGetAsync(String instrumentName, BigDecimal amount, BigDecimal price, final ApiCallback _callback) throws ApiException { @@ -1007,6 +1167,11 @@ public okhttp3.Call privateGetMarginsGetAsync(String instrumentName, BigDecimal * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetOpenOrdersByCurrencyGetCall(String currency, String kind, String type, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1070,6 +1235,11 @@ private okhttp3.Call privateGetOpenOrdersByCurrencyGetValidateBeforeCall(String * @param type Order type, default - `all` (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetOpenOrdersByCurrencyGet(String currency, String kind, String type) throws ApiException { ApiResponse localVarResp = privateGetOpenOrdersByCurrencyGetWithHttpInfo(currency, kind, type); @@ -1084,6 +1254,11 @@ public Object privateGetOpenOrdersByCurrencyGet(String currency, String kind, St * @param type Order type, default - `all` (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetOpenOrdersByCurrencyGetWithHttpInfo(String currency, String kind, String type) throws ApiException { okhttp3.Call localVarCall = privateGetOpenOrdersByCurrencyGetValidateBeforeCall(currency, kind, type, null); @@ -1100,6 +1275,11 @@ public ApiResponse privateGetOpenOrdersByCurrencyGetWithHttpInfo(String * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetOpenOrdersByCurrencyGetAsync(String currency, String kind, String type, final ApiCallback _callback) throws ApiException { @@ -1115,6 +1295,11 @@ public okhttp3.Call privateGetOpenOrdersByCurrencyGetAsync(String currency, Stri * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetOpenOrdersByInstrumentGetCall(String instrumentName, String type, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1173,6 +1358,11 @@ private okhttp3.Call privateGetOpenOrdersByInstrumentGetValidateBeforeCall(Strin * @param type Order type, default - `all` (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetOpenOrdersByInstrumentGet(String instrumentName, String type) throws ApiException { ApiResponse localVarResp = privateGetOpenOrdersByInstrumentGetWithHttpInfo(instrumentName, type); @@ -1186,6 +1376,11 @@ public Object privateGetOpenOrdersByInstrumentGet(String instrumentName, String * @param type Order type, default - `all` (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetOpenOrdersByInstrumentGetWithHttpInfo(String instrumentName, String type) throws ApiException { okhttp3.Call localVarCall = privateGetOpenOrdersByInstrumentGetValidateBeforeCall(instrumentName, type, null); @@ -1201,6 +1396,11 @@ public ApiResponse privateGetOpenOrdersByInstrumentGetWithHttpInfo(Strin * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetOpenOrdersByInstrumentGetAsync(String instrumentName, String type, final ApiCallback _callback) throws ApiException { @@ -1220,6 +1420,11 @@ public okhttp3.Call privateGetOpenOrdersByInstrumentGetAsync(String instrumentNa * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetOrderHistoryByCurrencyGetCall(String currency, String kind, Integer count, Integer offset, Boolean includeOld, Boolean includeUnfilled, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1298,6 +1503,11 @@ private okhttp3.Call privateGetOrderHistoryByCurrencyGetValidateBeforeCall(Strin * @param includeUnfilled Include in result fully unfilled closed orders, default - `false` (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetOrderHistoryByCurrencyGet(String currency, String kind, Integer count, Integer offset, Boolean includeOld, Boolean includeUnfilled) throws ApiException { ApiResponse localVarResp = privateGetOrderHistoryByCurrencyGetWithHttpInfo(currency, kind, count, offset, includeOld, includeUnfilled); @@ -1315,6 +1525,11 @@ public Object privateGetOrderHistoryByCurrencyGet(String currency, String kind, * @param includeUnfilled Include in result fully unfilled closed orders, default - `false` (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetOrderHistoryByCurrencyGetWithHttpInfo(String currency, String kind, Integer count, Integer offset, Boolean includeOld, Boolean includeUnfilled) throws ApiException { okhttp3.Call localVarCall = privateGetOrderHistoryByCurrencyGetValidateBeforeCall(currency, kind, count, offset, includeOld, includeUnfilled, null); @@ -1334,6 +1549,11 @@ public ApiResponse privateGetOrderHistoryByCurrencyGetWithHttpInfo(Strin * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetOrderHistoryByCurrencyGetAsync(String currency, String kind, Integer count, Integer offset, Boolean includeOld, Boolean includeUnfilled, final ApiCallback _callback) throws ApiException { @@ -1352,6 +1572,11 @@ public okhttp3.Call privateGetOrderHistoryByCurrencyGetAsync(String currency, St * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetOrderHistoryByInstrumentGetCall(String instrumentName, Integer count, Integer offset, Boolean includeOld, Boolean includeUnfilled, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1425,6 +1650,11 @@ private okhttp3.Call privateGetOrderHistoryByInstrumentGetValidateBeforeCall(Str * @param includeUnfilled Include in result fully unfilled closed orders, default - `false` (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetOrderHistoryByInstrumentGet(String instrumentName, Integer count, Integer offset, Boolean includeOld, Boolean includeUnfilled) throws ApiException { ApiResponse localVarResp = privateGetOrderHistoryByInstrumentGetWithHttpInfo(instrumentName, count, offset, includeOld, includeUnfilled); @@ -1441,6 +1671,11 @@ public Object privateGetOrderHistoryByInstrumentGet(String instrumentName, Integ * @param includeUnfilled Include in result fully unfilled closed orders, default - `false` (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetOrderHistoryByInstrumentGetWithHttpInfo(String instrumentName, Integer count, Integer offset, Boolean includeOld, Boolean includeUnfilled) throws ApiException { okhttp3.Call localVarCall = privateGetOrderHistoryByInstrumentGetValidateBeforeCall(instrumentName, count, offset, includeOld, includeUnfilled, null); @@ -1459,6 +1694,11 @@ public ApiResponse privateGetOrderHistoryByInstrumentGetWithHttpInfo(Str * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetOrderHistoryByInstrumentGetAsync(String instrumentName, Integer count, Integer offset, Boolean includeOld, Boolean includeUnfilled, final ApiCallback _callback) throws ApiException { @@ -1473,6 +1713,11 @@ public okhttp3.Call privateGetOrderHistoryByInstrumentGetAsync(String instrument * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetOrderMarginByIdsGetCall(List ids, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1526,6 +1771,11 @@ private okhttp3.Call privateGetOrderMarginByIdsGetValidateBeforeCall(List + Status Code Description Response Headers + 200 - + */ public Object privateGetOrderMarginByIdsGet(List ids) throws ApiException { ApiResponse localVarResp = privateGetOrderMarginByIdsGetWithHttpInfo(ids); @@ -1538,6 +1788,11 @@ public Object privateGetOrderMarginByIdsGet(List ids) throws ApiExceptio * @param ids Ids of orders (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetOrderMarginByIdsGetWithHttpInfo(List ids) throws ApiException { okhttp3.Call localVarCall = privateGetOrderMarginByIdsGetValidateBeforeCall(ids, null); @@ -1552,6 +1807,11 @@ public ApiResponse privateGetOrderMarginByIdsGetWithHttpInfo(List + Status Code Description Response Headers + 200 - + */ public okhttp3.Call privateGetOrderMarginByIdsGetAsync(List ids, final ApiCallback _callback) throws ApiException { @@ -1566,6 +1826,12 @@ public okhttp3.Call privateGetOrderMarginByIdsGetAsync(List ids, final A * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + +
Status Code Description Response Headers
200 ok response -
400 result when used via rest/HTTP -
*/ public okhttp3.Call privateGetOrderStateGetCall(String orderId, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1619,6 +1885,12 @@ private okhttp3.Call privateGetOrderStateGetValidateBeforeCall(String orderId, f * @param orderId The order id (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
Status Code Description Response Headers
200 ok response -
400 result when used via rest/HTTP -
*/ public Object privateGetOrderStateGet(String orderId) throws ApiException { ApiResponse localVarResp = privateGetOrderStateGetWithHttpInfo(orderId); @@ -1631,6 +1903,12 @@ public Object privateGetOrderStateGet(String orderId) throws ApiException { * @param orderId The order id (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
Status Code Description Response Headers
200 ok response -
400 result when used via rest/HTTP -
*/ public ApiResponse privateGetOrderStateGetWithHttpInfo(String orderId) throws ApiException { okhttp3.Call localVarCall = privateGetOrderStateGetValidateBeforeCall(orderId, null); @@ -1645,6 +1923,12 @@ public ApiResponse privateGetOrderStateGetWithHttpInfo(String orderId) t * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + +
Status Code Description Response Headers
200 ok response -
400 result when used via rest/HTTP -
*/ public okhttp3.Call privateGetOrderStateGetAsync(String orderId, final ApiCallback _callback) throws ApiException { @@ -1661,6 +1945,11 @@ public okhttp3.Call privateGetOrderStateGetAsync(String orderId, final ApiCallba * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetSettlementHistoryByCurrencyGetCall(String currency, String type, Integer count, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1724,6 +2013,11 @@ private okhttp3.Call privateGetSettlementHistoryByCurrencyGetValidateBeforeCall( * @param count Number of requested items, default - `20` (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetSettlementHistoryByCurrencyGet(String currency, String type, Integer count) throws ApiException { ApiResponse localVarResp = privateGetSettlementHistoryByCurrencyGetWithHttpInfo(currency, type, count); @@ -1738,6 +2032,11 @@ public Object privateGetSettlementHistoryByCurrencyGet(String currency, String t * @param count Number of requested items, default - `20` (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetSettlementHistoryByCurrencyGetWithHttpInfo(String currency, String type, Integer count) throws ApiException { okhttp3.Call localVarCall = privateGetSettlementHistoryByCurrencyGetValidateBeforeCall(currency, type, count, null); @@ -1754,6 +2053,11 @@ public ApiResponse privateGetSettlementHistoryByCurrencyGetWithHttpInfo( * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetSettlementHistoryByCurrencyGetAsync(String currency, String type, Integer count, final ApiCallback _callback) throws ApiException { @@ -1770,6 +2074,11 @@ public okhttp3.Call privateGetSettlementHistoryByCurrencyGetAsync(String currenc * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetSettlementHistoryByInstrumentGetCall(String instrumentName, String type, Integer count, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1833,6 +2142,11 @@ private okhttp3.Call privateGetSettlementHistoryByInstrumentGetValidateBeforeCal * @param count Number of requested items, default - `20` (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetSettlementHistoryByInstrumentGet(String instrumentName, String type, Integer count) throws ApiException { ApiResponse localVarResp = privateGetSettlementHistoryByInstrumentGetWithHttpInfo(instrumentName, type, count); @@ -1847,6 +2161,11 @@ public Object privateGetSettlementHistoryByInstrumentGet(String instrumentName, * @param count Number of requested items, default - `20` (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetSettlementHistoryByInstrumentGetWithHttpInfo(String instrumentName, String type, Integer count) throws ApiException { okhttp3.Call localVarCall = privateGetSettlementHistoryByInstrumentGetValidateBeforeCall(instrumentName, type, count, null); @@ -1863,6 +2182,11 @@ public ApiResponse privateGetSettlementHistoryByInstrumentGetWithHttpInf * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetSettlementHistoryByInstrumentGetAsync(String instrumentName, String type, Integer count, final ApiCallback _callback) throws ApiException { @@ -1883,6 +2207,11 @@ public okhttp3.Call privateGetSettlementHistoryByInstrumentGetAsync(String instr * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetUserTradesByCurrencyAndTimeGetCall(String currency, Integer startTimestamp, Integer endTimestamp, String kind, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1976,6 +2305,11 @@ private okhttp3.Call privateGetUserTradesByCurrencyAndTimeGetValidateBeforeCall( * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetUserTradesByCurrencyAndTimeGet(String currency, Integer startTimestamp, Integer endTimestamp, String kind, Integer count, Boolean includeOld, String sorting) throws ApiException { ApiResponse localVarResp = privateGetUserTradesByCurrencyAndTimeGetWithHttpInfo(currency, startTimestamp, endTimestamp, kind, count, includeOld, sorting); @@ -1994,6 +2328,11 @@ public Object privateGetUserTradesByCurrencyAndTimeGet(String currency, Integer * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetUserTradesByCurrencyAndTimeGetWithHttpInfo(String currency, Integer startTimestamp, Integer endTimestamp, String kind, Integer count, Boolean includeOld, String sorting) throws ApiException { okhttp3.Call localVarCall = privateGetUserTradesByCurrencyAndTimeGetValidateBeforeCall(currency, startTimestamp, endTimestamp, kind, count, includeOld, sorting, null); @@ -2014,6 +2353,11 @@ public ApiResponse privateGetUserTradesByCurrencyAndTimeGetWithHttpInfo( * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetUserTradesByCurrencyAndTimeGetAsync(String currency, Integer startTimestamp, Integer endTimestamp, String kind, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { @@ -2034,6 +2378,11 @@ public okhttp3.Call privateGetUserTradesByCurrencyAndTimeGetAsync(String currenc * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetUserTradesByCurrencyGetCall(String currency, String kind, String startId, String endId, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -2117,6 +2466,11 @@ private okhttp3.Call privateGetUserTradesByCurrencyGetValidateBeforeCall(String * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetUserTradesByCurrencyGet(String currency, String kind, String startId, String endId, Integer count, Boolean includeOld, String sorting) throws ApiException { ApiResponse localVarResp = privateGetUserTradesByCurrencyGetWithHttpInfo(currency, kind, startId, endId, count, includeOld, sorting); @@ -2135,6 +2489,11 @@ public Object privateGetUserTradesByCurrencyGet(String currency, String kind, St * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetUserTradesByCurrencyGetWithHttpInfo(String currency, String kind, String startId, String endId, Integer count, Boolean includeOld, String sorting) throws ApiException { okhttp3.Call localVarCall = privateGetUserTradesByCurrencyGetValidateBeforeCall(currency, kind, startId, endId, count, includeOld, sorting, null); @@ -2155,6 +2514,11 @@ public ApiResponse privateGetUserTradesByCurrencyGetWithHttpInfo(String * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetUserTradesByCurrencyGetAsync(String currency, String kind, String startId, String endId, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { @@ -2174,6 +2538,11 @@ public okhttp3.Call privateGetUserTradesByCurrencyGetAsync(String currency, Stri * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetUserTradesByInstrumentAndTimeGetCall(String instrumentName, Integer startTimestamp, Integer endTimestamp, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -2262,6 +2631,11 @@ private okhttp3.Call privateGetUserTradesByInstrumentAndTimeGetValidateBeforeCal * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetUserTradesByInstrumentAndTimeGet(String instrumentName, Integer startTimestamp, Integer endTimestamp, Integer count, Boolean includeOld, String sorting) throws ApiException { ApiResponse localVarResp = privateGetUserTradesByInstrumentAndTimeGetWithHttpInfo(instrumentName, startTimestamp, endTimestamp, count, includeOld, sorting); @@ -2279,6 +2653,11 @@ public Object privateGetUserTradesByInstrumentAndTimeGet(String instrumentName, * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetUserTradesByInstrumentAndTimeGetWithHttpInfo(String instrumentName, Integer startTimestamp, Integer endTimestamp, Integer count, Boolean includeOld, String sorting) throws ApiException { okhttp3.Call localVarCall = privateGetUserTradesByInstrumentAndTimeGetValidateBeforeCall(instrumentName, startTimestamp, endTimestamp, count, includeOld, sorting, null); @@ -2298,6 +2677,11 @@ public ApiResponse privateGetUserTradesByInstrumentAndTimeGetWithHttpInf * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetUserTradesByInstrumentAndTimeGetAsync(String instrumentName, Integer startTimestamp, Integer endTimestamp, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { @@ -2317,6 +2701,11 @@ public okhttp3.Call privateGetUserTradesByInstrumentAndTimeGetAsync(String instr * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetUserTradesByInstrumentGetCall(String instrumentName, Integer startSeq, Integer endSeq, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -2395,6 +2784,11 @@ private okhttp3.Call privateGetUserTradesByInstrumentGetValidateBeforeCall(Strin * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetUserTradesByInstrumentGet(String instrumentName, Integer startSeq, Integer endSeq, Integer count, Boolean includeOld, String sorting) throws ApiException { ApiResponse localVarResp = privateGetUserTradesByInstrumentGetWithHttpInfo(instrumentName, startSeq, endSeq, count, includeOld, sorting); @@ -2412,6 +2806,11 @@ public Object privateGetUserTradesByInstrumentGet(String instrumentName, Integer * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetUserTradesByInstrumentGetWithHttpInfo(String instrumentName, Integer startSeq, Integer endSeq, Integer count, Boolean includeOld, String sorting) throws ApiException { okhttp3.Call localVarCall = privateGetUserTradesByInstrumentGetValidateBeforeCall(instrumentName, startSeq, endSeq, count, includeOld, sorting, null); @@ -2431,6 +2830,11 @@ public ApiResponse privateGetUserTradesByInstrumentGetWithHttpInfo(Strin * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetUserTradesByInstrumentGetAsync(String instrumentName, Integer startSeq, Integer endSeq, Integer count, Boolean includeOld, String sorting, final ApiCallback _callback) throws ApiException { @@ -2446,6 +2850,11 @@ public okhttp3.Call privateGetUserTradesByInstrumentGetAsync(String instrumentNa * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetUserTradesByOrderGetCall(String orderId, String sorting, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -2504,6 +2913,11 @@ private okhttp3.Call privateGetUserTradesByOrderGetValidateBeforeCall(String ord * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetUserTradesByOrderGet(String orderId, String sorting) throws ApiException { ApiResponse localVarResp = privateGetUserTradesByOrderGetWithHttpInfo(orderId, sorting); @@ -2517,6 +2931,11 @@ public Object privateGetUserTradesByOrderGet(String orderId, String sorting) thr * @param sorting Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetUserTradesByOrderGetWithHttpInfo(String orderId, String sorting) throws ApiException { okhttp3.Call localVarCall = privateGetUserTradesByOrderGetValidateBeforeCall(orderId, sorting, null); @@ -2532,6 +2951,11 @@ public ApiResponse privateGetUserTradesByOrderGetWithHttpInfo(String ord * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetUserTradesByOrderGetAsync(String orderId, String sorting, final ApiCallback _callback) throws ApiException { @@ -2557,6 +2981,11 @@ public okhttp3.Call privateGetUserTradesByOrderGetAsync(String orderId, String s * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateSellGetCall(String instrumentName, BigDecimal amount, String type, String label, BigDecimal price, String timeInForce, BigDecimal maxShow, Boolean postOnly, Boolean reduceOnly, BigDecimal stopPrice, String trigger, String advanced, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -2670,6 +3099,11 @@ private okhttp3.Call privateSellGetValidateBeforeCall(String instrumentName, Big * @param advanced Advanced option order type. (Only for options) (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateSellGet(String instrumentName, BigDecimal amount, String type, String label, BigDecimal price, String timeInForce, BigDecimal maxShow, Boolean postOnly, Boolean reduceOnly, BigDecimal stopPrice, String trigger, String advanced) throws ApiException { ApiResponse localVarResp = privateSellGetWithHttpInfo(instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced); @@ -2693,6 +3127,11 @@ public Object privateSellGet(String instrumentName, BigDecimal amount, String ty * @param advanced Advanced option order type. (Only for options) (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateSellGetWithHttpInfo(String instrumentName, BigDecimal amount, String type, String label, BigDecimal price, String timeInForce, BigDecimal maxShow, Boolean postOnly, Boolean reduceOnly, BigDecimal stopPrice, String trigger, String advanced) throws ApiException { okhttp3.Call localVarCall = privateSellGetValidateBeforeCall(instrumentName, amount, type, label, price, timeInForce, maxShow, postOnly, reduceOnly, stopPrice, trigger, advanced, null); @@ -2718,6 +3157,11 @@ public ApiResponse privateSellGetWithHttpInfo(String instrumentName, Big * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateSellGetAsync(String instrumentName, BigDecimal amount, String type, String label, BigDecimal price, String timeInForce, BigDecimal maxShow, Boolean postOnly, Boolean reduceOnly, BigDecimal stopPrice, String trigger, String advanced, final ApiCallback _callback) throws ApiException { diff --git a/java/src/main/java/org/openapitools/client/api/WalletApi.java b/java/src/main/java/org/openapitools/client/api/WalletApi.java index 7dc7450..6efb3c9 100644 --- a/java/src/main/java/org/openapitools/client/api/WalletApi.java +++ b/java/src/main/java/org/openapitools/client/api/WalletApi.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -64,6 +64,11 @@ public void setApiClient(ApiClient apiClient) { * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateAddToAddressBookGetCall(String currency, String type, String address, String name, String tfa, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -152,6 +157,11 @@ private okhttp3.Call privateAddToAddressBookGetValidateBeforeCall(String currenc * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateAddToAddressBookGet(String currency, String type, String address, String name, String tfa) throws ApiException { ApiResponse localVarResp = privateAddToAddressBookGetWithHttpInfo(currency, type, address, name, tfa); @@ -168,6 +178,11 @@ public Object privateAddToAddressBookGet(String currency, String type, String ad * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateAddToAddressBookGetWithHttpInfo(String currency, String type, String address, String name, String tfa) throws ApiException { okhttp3.Call localVarCall = privateAddToAddressBookGetValidateBeforeCall(currency, type, address, name, tfa, null); @@ -186,6 +201,11 @@ public ApiResponse privateAddToAddressBookGetWithHttpInfo(String currenc * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateAddToAddressBookGetAsync(String currency, String type, String address, String name, String tfa, final ApiCallback _callback) throws ApiException { @@ -202,6 +222,11 @@ public okhttp3.Call privateAddToAddressBookGetAsync(String currency, String type * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateCancelTransferByIdGetCall(String currency, Integer id, String tfa, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -270,6 +295,11 @@ private okhttp3.Call privateCancelTransferByIdGetValidateBeforeCall(String curre * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateCancelTransferByIdGet(String currency, Integer id, String tfa) throws ApiException { ApiResponse localVarResp = privateCancelTransferByIdGetWithHttpInfo(currency, id, tfa); @@ -284,6 +314,11 @@ public Object privateCancelTransferByIdGet(String currency, Integer id, String t * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateCancelTransferByIdGetWithHttpInfo(String currency, Integer id, String tfa) throws ApiException { okhttp3.Call localVarCall = privateCancelTransferByIdGetValidateBeforeCall(currency, id, tfa, null); @@ -300,6 +335,11 @@ public ApiResponse privateCancelTransferByIdGetWithHttpInfo(String curre * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateCancelTransferByIdGetAsync(String currency, Integer id, String tfa, final ApiCallback _callback) throws ApiException { @@ -315,6 +355,11 @@ public okhttp3.Call privateCancelTransferByIdGetAsync(String currency, Integer i * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateCancelWithdrawalGetCall(String currency, BigDecimal id, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -378,6 +423,11 @@ private okhttp3.Call privateCancelWithdrawalGetValidateBeforeCall(String currenc * @param id The withdrawal id (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateCancelWithdrawalGet(String currency, BigDecimal id) throws ApiException { ApiResponse localVarResp = privateCancelWithdrawalGetWithHttpInfo(currency, id); @@ -391,6 +441,11 @@ public Object privateCancelWithdrawalGet(String currency, BigDecimal id) throws * @param id The withdrawal id (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateCancelWithdrawalGetWithHttpInfo(String currency, BigDecimal id) throws ApiException { okhttp3.Call localVarCall = privateCancelWithdrawalGetValidateBeforeCall(currency, id, null); @@ -406,6 +461,11 @@ public ApiResponse privateCancelWithdrawalGetWithHttpInfo(String currenc * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateCancelWithdrawalGetAsync(String currency, BigDecimal id, final ApiCallback _callback) throws ApiException { @@ -420,6 +480,11 @@ public okhttp3.Call privateCancelWithdrawalGetAsync(String currency, BigDecimal * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateCreateDepositAddressGetCall(String currency, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -473,6 +538,11 @@ private okhttp3.Call privateCreateDepositAddressGetValidateBeforeCall(String cur * @param currency The currency symbol (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateCreateDepositAddressGet(String currency) throws ApiException { ApiResponse localVarResp = privateCreateDepositAddressGetWithHttpInfo(currency); @@ -485,6 +555,11 @@ public Object privateCreateDepositAddressGet(String currency) throws ApiExceptio * @param currency The currency symbol (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateCreateDepositAddressGetWithHttpInfo(String currency) throws ApiException { okhttp3.Call localVarCall = privateCreateDepositAddressGetValidateBeforeCall(currency, null); @@ -499,6 +574,11 @@ public ApiResponse privateCreateDepositAddressGetWithHttpInfo(String cur * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateCreateDepositAddressGetAsync(String currency, final ApiCallback _callback) throws ApiException { @@ -514,6 +594,11 @@ public okhttp3.Call privateCreateDepositAddressGetAsync(String currency, final A * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetAddressBookGetCall(String currency, String type, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -577,6 +662,11 @@ private okhttp3.Call privateGetAddressBookGetValidateBeforeCall(String currency, * @param type Address book type (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetAddressBookGet(String currency, String type) throws ApiException { ApiResponse localVarResp = privateGetAddressBookGetWithHttpInfo(currency, type); @@ -590,6 +680,11 @@ public Object privateGetAddressBookGet(String currency, String type) throws ApiE * @param type Address book type (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetAddressBookGetWithHttpInfo(String currency, String type) throws ApiException { okhttp3.Call localVarCall = privateGetAddressBookGetValidateBeforeCall(currency, type, null); @@ -605,6 +700,11 @@ public ApiResponse privateGetAddressBookGetWithHttpInfo(String currency, * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetAddressBookGetAsync(String currency, String type, final ApiCallback _callback) throws ApiException { @@ -619,6 +719,11 @@ public okhttp3.Call privateGetAddressBookGetAsync(String currency, String type, * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetCurrentDepositAddressGetCall(String currency, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -672,6 +777,11 @@ private okhttp3.Call privateGetCurrentDepositAddressGetValidateBeforeCall(String * @param currency The currency symbol (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetCurrentDepositAddressGet(String currency) throws ApiException { ApiResponse localVarResp = privateGetCurrentDepositAddressGetWithHttpInfo(currency); @@ -684,6 +794,11 @@ public Object privateGetCurrentDepositAddressGet(String currency) throws ApiExce * @param currency The currency symbol (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetCurrentDepositAddressGetWithHttpInfo(String currency) throws ApiException { okhttp3.Call localVarCall = privateGetCurrentDepositAddressGetValidateBeforeCall(currency, null); @@ -698,6 +813,11 @@ public ApiResponse privateGetCurrentDepositAddressGetWithHttpInfo(String * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetCurrentDepositAddressGetAsync(String currency, final ApiCallback _callback) throws ApiException { @@ -714,6 +834,11 @@ public okhttp3.Call privateGetCurrentDepositAddressGetAsync(String currency, fin * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetDepositsGetCall(String currency, Integer count, Integer offset, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -777,6 +902,11 @@ private okhttp3.Call privateGetDepositsGetValidateBeforeCall(String currency, In * @param offset The offset for pagination, default - `0` (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetDepositsGet(String currency, Integer count, Integer offset) throws ApiException { ApiResponse localVarResp = privateGetDepositsGetWithHttpInfo(currency, count, offset); @@ -791,6 +921,11 @@ public Object privateGetDepositsGet(String currency, Integer count, Integer offs * @param offset The offset for pagination, default - `0` (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetDepositsGetWithHttpInfo(String currency, Integer count, Integer offset) throws ApiException { okhttp3.Call localVarCall = privateGetDepositsGetValidateBeforeCall(currency, count, offset, null); @@ -807,6 +942,11 @@ public ApiResponse privateGetDepositsGetWithHttpInfo(String currency, In * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetDepositsGetAsync(String currency, Integer count, Integer offset, final ApiCallback _callback) throws ApiException { @@ -823,6 +963,11 @@ public okhttp3.Call privateGetDepositsGetAsync(String currency, Integer count, I * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetTransfersGetCall(String currency, Integer count, Integer offset, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -886,6 +1031,11 @@ private okhttp3.Call privateGetTransfersGetValidateBeforeCall(String currency, I * @param offset The offset for pagination, default - `0` (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetTransfersGet(String currency, Integer count, Integer offset) throws ApiException { ApiResponse localVarResp = privateGetTransfersGetWithHttpInfo(currency, count, offset); @@ -900,6 +1050,11 @@ public Object privateGetTransfersGet(String currency, Integer count, Integer off * @param offset The offset for pagination, default - `0` (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetTransfersGetWithHttpInfo(String currency, Integer count, Integer offset) throws ApiException { okhttp3.Call localVarCall = privateGetTransfersGetValidateBeforeCall(currency, count, offset, null); @@ -916,6 +1071,11 @@ public ApiResponse privateGetTransfersGetWithHttpInfo(String currency, I * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetTransfersGetAsync(String currency, Integer count, Integer offset, final ApiCallback _callback) throws ApiException { @@ -932,6 +1092,11 @@ public okhttp3.Call privateGetTransfersGetAsync(String currency, Integer count, * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetWithdrawalsGetCall(String currency, Integer count, Integer offset, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -995,6 +1160,11 @@ private okhttp3.Call privateGetWithdrawalsGetValidateBeforeCall(String currency, * @param offset The offset for pagination, default - `0` (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateGetWithdrawalsGet(String currency, Integer count, Integer offset) throws ApiException { ApiResponse localVarResp = privateGetWithdrawalsGetWithHttpInfo(currency, count, offset); @@ -1009,6 +1179,11 @@ public Object privateGetWithdrawalsGet(String currency, Integer count, Integer o * @param offset The offset for pagination, default - `0` (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateGetWithdrawalsGetWithHttpInfo(String currency, Integer count, Integer offset) throws ApiException { okhttp3.Call localVarCall = privateGetWithdrawalsGetValidateBeforeCall(currency, count, offset, null); @@ -1025,6 +1200,11 @@ public ApiResponse privateGetWithdrawalsGetWithHttpInfo(String currency, * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateGetWithdrawalsGetAsync(String currency, Integer count, Integer offset, final ApiCallback _callback) throws ApiException { @@ -1042,6 +1222,11 @@ public okhttp3.Call privateGetWithdrawalsGetAsync(String currency, Integer count * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateRemoveFromAddressBookGetCall(String currency, String type, String address, String tfa, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1120,6 +1305,11 @@ private okhttp3.Call privateRemoveFromAddressBookGetValidateBeforeCall(String cu * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateRemoveFromAddressBookGet(String currency, String type, String address, String tfa) throws ApiException { ApiResponse localVarResp = privateRemoveFromAddressBookGetWithHttpInfo(currency, type, address, tfa); @@ -1135,6 +1325,11 @@ public Object privateRemoveFromAddressBookGet(String currency, String type, Stri * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateRemoveFromAddressBookGetWithHttpInfo(String currency, String type, String address, String tfa) throws ApiException { okhttp3.Call localVarCall = privateRemoveFromAddressBookGetValidateBeforeCall(currency, type, address, tfa, null); @@ -1152,6 +1347,11 @@ public ApiResponse privateRemoveFromAddressBookGetWithHttpInfo(String cu * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateRemoveFromAddressBookGetAsync(String currency, String type, String address, String tfa, final ApiCallback _callback) throws ApiException { @@ -1168,6 +1368,11 @@ public okhttp3.Call privateRemoveFromAddressBookGetAsync(String currency, String * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateSubmitTransferToSubaccountGetCall(String currency, BigDecimal amount, Integer destination, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1241,6 +1446,11 @@ private okhttp3.Call privateSubmitTransferToSubaccountGetValidateBeforeCall(Stri * @param destination Id of destination subaccount (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public Object privateSubmitTransferToSubaccountGet(String currency, BigDecimal amount, Integer destination) throws ApiException { ApiResponse localVarResp = privateSubmitTransferToSubaccountGetWithHttpInfo(currency, amount, destination); @@ -1255,6 +1465,11 @@ public Object privateSubmitTransferToSubaccountGet(String currency, BigDecimal a * @param destination Id of destination subaccount (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public ApiResponse privateSubmitTransferToSubaccountGetWithHttpInfo(String currency, BigDecimal amount, Integer destination) throws ApiException { okhttp3.Call localVarCall = privateSubmitTransferToSubaccountGetValidateBeforeCall(currency, amount, destination, null); @@ -1271,6 +1486,11 @@ public ApiResponse privateSubmitTransferToSubaccountGetWithHttpInfo(Stri * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 ok response -
*/ public okhttp3.Call privateSubmitTransferToSubaccountGetAsync(String currency, BigDecimal amount, Integer destination, final ApiCallback _callback) throws ApiException { @@ -1288,6 +1508,11 @@ public okhttp3.Call privateSubmitTransferToSubaccountGetAsync(String currency, B * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateSubmitTransferToUserGetCall(String currency, BigDecimal amount, String destination, String tfa, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1366,6 +1591,11 @@ private okhttp3.Call privateSubmitTransferToUserGetValidateBeforeCall(String cur * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateSubmitTransferToUserGet(String currency, BigDecimal amount, String destination, String tfa) throws ApiException { ApiResponse localVarResp = privateSubmitTransferToUserGetWithHttpInfo(currency, amount, destination, tfa); @@ -1381,6 +1611,11 @@ public Object privateSubmitTransferToUserGet(String currency, BigDecimal amount, * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateSubmitTransferToUserGetWithHttpInfo(String currency, BigDecimal amount, String destination, String tfa) throws ApiException { okhttp3.Call localVarCall = privateSubmitTransferToUserGetValidateBeforeCall(currency, amount, destination, tfa, null); @@ -1398,6 +1633,11 @@ public ApiResponse privateSubmitTransferToUserGetWithHttpInfo(String cur * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateSubmitTransferToUserGetAsync(String currency, BigDecimal amount, String destination, String tfa, final ApiCallback _callback) throws ApiException { @@ -1413,6 +1653,11 @@ public okhttp3.Call privateSubmitTransferToUserGetAsync(String currency, BigDeci * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateToggleDepositAddressCreationGetCall(String currency, Boolean state, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1476,6 +1721,11 @@ private okhttp3.Call privateToggleDepositAddressCreationGetValidateBeforeCall(St * @param state (required) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateToggleDepositAddressCreationGet(String currency, Boolean state) throws ApiException { ApiResponse localVarResp = privateToggleDepositAddressCreationGetWithHttpInfo(currency, state); @@ -1489,6 +1739,11 @@ public Object privateToggleDepositAddressCreationGet(String currency, Boolean st * @param state (required) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateToggleDepositAddressCreationGetWithHttpInfo(String currency, Boolean state) throws ApiException { okhttp3.Call localVarCall = privateToggleDepositAddressCreationGetValidateBeforeCall(currency, state, null); @@ -1504,6 +1759,11 @@ public ApiResponse privateToggleDepositAddressCreationGetWithHttpInfo(St * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateToggleDepositAddressCreationGetAsync(String currency, Boolean state, final ApiCallback _callback) throws ApiException { @@ -1522,6 +1782,11 @@ public okhttp3.Call privateToggleDepositAddressCreationGetAsync(String currency, * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateWithdrawGetCall(String currency, String address, BigDecimal amount, String priority, String tfa, final ApiCallback _callback) throws ApiException { Object localVarPostBody = new Object(); @@ -1605,6 +1870,11 @@ private okhttp3.Call privateWithdrawGetValidateBeforeCall(String currency, Strin * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return Object * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public Object privateWithdrawGet(String currency, String address, BigDecimal amount, String priority, String tfa) throws ApiException { ApiResponse localVarResp = privateWithdrawGetWithHttpInfo(currency, address, amount, priority, tfa); @@ -1621,6 +1891,11 @@ public Object privateWithdrawGet(String currency, String address, BigDecimal amo * @param tfa TFA code, required when TFA is enabled for current account (optional) * @return ApiResponse<Object> * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public ApiResponse privateWithdrawGetWithHttpInfo(String currency, String address, BigDecimal amount, String priority, String tfa) throws ApiException { okhttp3.Call localVarCall = privateWithdrawGetValidateBeforeCall(currency, address, amount, priority, tfa, null); @@ -1639,6 +1914,11 @@ public ApiResponse privateWithdrawGetWithHttpInfo(String currency, Strin * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 -
*/ public okhttp3.Call privateWithdrawGetAsync(String currency, String address, BigDecimal amount, String priority, String tfa, final ApiCallback _callback) throws ApiException { diff --git a/java/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java b/java/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java index 7fb08f1..d365f16 100644 --- a/java/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java +++ b/java/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -18,7 +18,7 @@ import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/java/src/main/java/org/openapitools/client/auth/Authentication.java b/java/src/main/java/org/openapitools/client/auth/Authentication.java index 3bf1347..d8fa061 100644 --- a/java/src/main/java/org/openapitools/client/auth/Authentication.java +++ b/java/src/main/java/org/openapitools/client/auth/Authentication.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/java/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java b/java/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java index ce4da37..cf886bc 100644 --- a/java/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java +++ b/java/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/java/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/java/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java index 57e7172..8173280 100644 --- a/java/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +++ b/java/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -18,7 +18,7 @@ import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class HttpBearerAuth implements Authentication { private final String scheme; private String bearerToken; diff --git a/java/src/main/java/org/openapitools/client/model/AddressBookItem.java b/java/src/main/java/org/openapitools/client/model/AddressBookItem.java index 2bd5322..5205c15 100644 --- a/java/src/main/java/org/openapitools/client/model/AddressBookItem.java +++ b/java/src/main/java/org/openapitools/client/model/AddressBookItem.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -27,7 +27,7 @@ /** * AddressBookItem */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class AddressBookItem { /** * Currency, i.e `\"BTC\"`, `\"ETH\"` diff --git a/java/src/main/java/org/openapitools/client/model/BookSummary.java b/java/src/main/java/org/openapitools/client/model/BookSummary.java index b755b76..3807b7f 100644 --- a/java/src/main/java/org/openapitools/client/model/BookSummary.java +++ b/java/src/main/java/org/openapitools/client/model/BookSummary.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -28,7 +28,7 @@ /** * BookSummary */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class BookSummary { public static final String SERIALIZED_NAME_UNDERLYING_INDEX = "underlying_index"; @SerializedName(SERIALIZED_NAME_UNDERLYING_INDEX) diff --git a/java/src/main/java/org/openapitools/client/model/Currency.java b/java/src/main/java/org/openapitools/client/model/Currency.java index 16ca917..8f3f1c5 100644 --- a/java/src/main/java/org/openapitools/client/model/Currency.java +++ b/java/src/main/java/org/openapitools/client/model/Currency.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -31,7 +31,7 @@ /** * Currency */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class Currency { public static final String SERIALIZED_NAME_MIN_CONFIRMATIONS = "min_confirmations"; @SerializedName(SERIALIZED_NAME_MIN_CONFIRMATIONS) diff --git a/java/src/main/java/org/openapitools/client/model/CurrencyPortfolio.java b/java/src/main/java/org/openapitools/client/model/CurrencyPortfolio.java index 68bb866..7d4976a 100644 --- a/java/src/main/java/org/openapitools/client/model/CurrencyPortfolio.java +++ b/java/src/main/java/org/openapitools/client/model/CurrencyPortfolio.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -28,7 +28,7 @@ /** * CurrencyPortfolio */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class CurrencyPortfolio { public static final String SERIALIZED_NAME_MAINTENANCE_MARGIN = "maintenance_margin"; @SerializedName(SERIALIZED_NAME_MAINTENANCE_MARGIN) diff --git a/java/src/main/java/org/openapitools/client/model/CurrencyWithdrawalPriorities.java b/java/src/main/java/org/openapitools/client/model/CurrencyWithdrawalPriorities.java index d238207..c929dff 100644 --- a/java/src/main/java/org/openapitools/client/model/CurrencyWithdrawalPriorities.java +++ b/java/src/main/java/org/openapitools/client/model/CurrencyWithdrawalPriorities.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -28,7 +28,7 @@ /** * CurrencyWithdrawalPriorities */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class CurrencyWithdrawalPriorities { public static final String SERIALIZED_NAME_NAME = "name"; @SerializedName(SERIALIZED_NAME_NAME) diff --git a/java/src/main/java/org/openapitools/client/model/Deposit.java b/java/src/main/java/org/openapitools/client/model/Deposit.java index e358310..e70d60d 100644 --- a/java/src/main/java/org/openapitools/client/model/Deposit.java +++ b/java/src/main/java/org/openapitools/client/model/Deposit.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -28,7 +28,7 @@ /** * Deposit */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class Deposit { public static final String SERIALIZED_NAME_UPDATED_TIMESTAMP = "updated_timestamp"; @SerializedName(SERIALIZED_NAME_UPDATED_TIMESTAMP) diff --git a/java/src/main/java/org/openapitools/client/model/Instrument.java b/java/src/main/java/org/openapitools/client/model/Instrument.java index 0bcb7cd..659366b 100644 --- a/java/src/main/java/org/openapitools/client/model/Instrument.java +++ b/java/src/main/java/org/openapitools/client/model/Instrument.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -28,7 +28,7 @@ /** * Instrument */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class Instrument { /** * The currency in which the instrument prices are quoted. diff --git a/java/src/main/java/org/openapitools/client/model/KeyNumberPair.java b/java/src/main/java/org/openapitools/client/model/KeyNumberPair.java index fdcbc98..b818c96 100644 --- a/java/src/main/java/org/openapitools/client/model/KeyNumberPair.java +++ b/java/src/main/java/org/openapitools/client/model/KeyNumberPair.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -28,7 +28,7 @@ /** * KeyNumberPair */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class KeyNumberPair { public static final String SERIALIZED_NAME_NAME = "name"; @SerializedName(SERIALIZED_NAME_NAME) diff --git a/java/src/main/java/org/openapitools/client/model/Order.java b/java/src/main/java/org/openapitools/client/model/Order.java index 115e620..a75ada2 100644 --- a/java/src/main/java/org/openapitools/client/model/Order.java +++ b/java/src/main/java/org/openapitools/client/model/Order.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -28,7 +28,7 @@ /** * Order */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class Order { /** * direction, `buy` or `sell` diff --git a/java/src/main/java/org/openapitools/client/model/OrderIdInitialMarginPair.java b/java/src/main/java/org/openapitools/client/model/OrderIdInitialMarginPair.java index cef3781..6508a9d 100644 --- a/java/src/main/java/org/openapitools/client/model/OrderIdInitialMarginPair.java +++ b/java/src/main/java/org/openapitools/client/model/OrderIdInitialMarginPair.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -28,7 +28,7 @@ /** * OrderIdInitialMarginPair */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class OrderIdInitialMarginPair { public static final String SERIALIZED_NAME_ORDER_ID = "order_id"; @SerializedName(SERIALIZED_NAME_ORDER_ID) diff --git a/java/src/main/java/org/openapitools/client/model/Portfolio.java b/java/src/main/java/org/openapitools/client/model/Portfolio.java index a12f8bf..a9ae39d 100644 --- a/java/src/main/java/org/openapitools/client/model/Portfolio.java +++ b/java/src/main/java/org/openapitools/client/model/Portfolio.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -28,7 +28,7 @@ /** * Portfolio */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class Portfolio { public static final String SERIALIZED_NAME_ETH = "eth"; @SerializedName(SERIALIZED_NAME_ETH) diff --git a/java/src/main/java/org/openapitools/client/model/PortfolioEth.java b/java/src/main/java/org/openapitools/client/model/PortfolioEth.java index b1ab288..acef3e8 100644 --- a/java/src/main/java/org/openapitools/client/model/PortfolioEth.java +++ b/java/src/main/java/org/openapitools/client/model/PortfolioEth.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -28,7 +28,7 @@ /** * PortfolioEth */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class PortfolioEth { public static final String SERIALIZED_NAME_MAINTENANCE_MARGIN = "maintenance_margin"; @SerializedName(SERIALIZED_NAME_MAINTENANCE_MARGIN) diff --git a/java/src/main/java/org/openapitools/client/model/Position.java b/java/src/main/java/org/openapitools/client/model/Position.java index 986a239..8a69000 100644 --- a/java/src/main/java/org/openapitools/client/model/Position.java +++ b/java/src/main/java/org/openapitools/client/model/Position.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -28,7 +28,7 @@ /** * Position */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class Position { /** * direction, `buy` or `sell` diff --git a/java/src/main/java/org/openapitools/client/model/PublicTrade.java b/java/src/main/java/org/openapitools/client/model/PublicTrade.java index 639360a..78b7466 100644 --- a/java/src/main/java/org/openapitools/client/model/PublicTrade.java +++ b/java/src/main/java/org/openapitools/client/model/PublicTrade.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -28,7 +28,7 @@ /** * PublicTrade */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class PublicTrade { /** * Trade direction of the taker diff --git a/java/src/main/java/org/openapitools/client/model/Settlement.java b/java/src/main/java/org/openapitools/client/model/Settlement.java index 73aa783..367ea04 100644 --- a/java/src/main/java/org/openapitools/client/model/Settlement.java +++ b/java/src/main/java/org/openapitools/client/model/Settlement.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -28,7 +28,7 @@ /** * Settlement */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class Settlement { public static final String SERIALIZED_NAME_SESSION_PROFIT_LOSS = "session_profit_loss"; @SerializedName(SERIALIZED_NAME_SESSION_PROFIT_LOSS) diff --git a/java/src/main/java/org/openapitools/client/model/TradesVolumes.java b/java/src/main/java/org/openapitools/client/model/TradesVolumes.java index 0577a33..49b7d43 100644 --- a/java/src/main/java/org/openapitools/client/model/TradesVolumes.java +++ b/java/src/main/java/org/openapitools/client/model/TradesVolumes.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -28,7 +28,7 @@ /** * TradesVolumes */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class TradesVolumes { public static final String SERIALIZED_NAME_CALLS_VOLUME = "calls_volume"; @SerializedName(SERIALIZED_NAME_CALLS_VOLUME) diff --git a/java/src/main/java/org/openapitools/client/model/TransferItem.java b/java/src/main/java/org/openapitools/client/model/TransferItem.java index eb0dbf7..d7f6862 100644 --- a/java/src/main/java/org/openapitools/client/model/TransferItem.java +++ b/java/src/main/java/org/openapitools/client/model/TransferItem.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -28,7 +28,7 @@ /** * TransferItem */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class TransferItem { public static final String SERIALIZED_NAME_UPDATED_TIMESTAMP = "updated_timestamp"; @SerializedName(SERIALIZED_NAME_UPDATED_TIMESTAMP) diff --git a/java/src/main/java/org/openapitools/client/model/Types.java b/java/src/main/java/org/openapitools/client/model/Types.java index 2d546dc..d590cfc 100644 --- a/java/src/main/java/org/openapitools/client/model/Types.java +++ b/java/src/main/java/org/openapitools/client/model/Types.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -19,7 +19,7 @@ /** * Types */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class Types { @Override diff --git a/java/src/main/java/org/openapitools/client/model/UserTrade.java b/java/src/main/java/org/openapitools/client/model/UserTrade.java index 4fc10e9..69f48d4 100644 --- a/java/src/main/java/org/openapitools/client/model/UserTrade.java +++ b/java/src/main/java/org/openapitools/client/model/UserTrade.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -28,7 +28,7 @@ /** * UserTrade */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class UserTrade { /** * Trade direction of the taker diff --git a/java/src/main/java/org/openapitools/client/model/Withdrawal.java b/java/src/main/java/org/openapitools/client/model/Withdrawal.java index 423646c..486fe8d 100644 --- a/java/src/main/java/org/openapitools/client/model/Withdrawal.java +++ b/java/src/main/java/org/openapitools/client/model/Withdrawal.java @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -28,7 +28,7 @@ /** * Withdrawal */ -@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-05-31T10:31:59.717+02:00[Europe/Paris]") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2019-06-03T12:41:14.884+02:00[Europe/Paris]") public class Withdrawal { public static final String SERIALIZED_NAME_UPDATED_TIMESTAMP = "updated_timestamp"; @SerializedName(SERIALIZED_NAME_UPDATED_TIMESTAMP) diff --git a/javascript/.openapi-generator/VERSION b/javascript/.openapi-generator/VERSION index afa6365..d96260b 100644 --- a/javascript/.openapi-generator/VERSION +++ b/javascript/.openapi-generator/VERSION @@ -1 +1 @@ -4.0.0-SNAPSHOT \ No newline at end of file +4.0.2-SNAPSHOT \ No newline at end of file diff --git a/javascript/src/ApiClient.js b/javascript/src/ApiClient.js index 92a4a6f..fe742e9 100644 --- a/javascript/src/ApiClient.js +++ b/javascript/src/ApiClient.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -577,7 +577,8 @@ class ApiClient { // go through variable and assign a value for (var variable_name in server['variables']) { if (variable_name in variables) { - if (server['variables'][variable_name]['enum_values'].includes(variables[variable_name])) { + let variable = server['variables'][variable_name]; + if ( !('enum_values' in variable) || variable['enum_values'].includes(variables[variable_name]) ) { url = url.replace("{" + variable_name + "}", variables[variable_name]); } else { throw new Error("The variable `" + variable_name + "` in the host URL has invalid value " + variables[variable_name] + ". Must be " + server['variables'][variable_name]['enum_values'] + "."); diff --git a/javascript/src/api/AccountManagementApi.js b/javascript/src/api/AccountManagementApi.js index cc7dd90..146fd90 100644 --- a/javascript/src/api/AccountManagementApi.js +++ b/javascript/src/api/AccountManagementApi.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/api/AuthenticationApi.js b/javascript/src/api/AuthenticationApi.js index d99d966..f6fffd4 100644 --- a/javascript/src/api/AuthenticationApi.js +++ b/javascript/src/api/AuthenticationApi.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/api/InternalApi.js b/javascript/src/api/InternalApi.js index d8f04f8..a84295f 100644 --- a/javascript/src/api/InternalApi.js +++ b/javascript/src/api/InternalApi.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/api/MarketDataApi.js b/javascript/src/api/MarketDataApi.js index c2d06ad..ef9b1c6 100644 --- a/javascript/src/api/MarketDataApi.js +++ b/javascript/src/api/MarketDataApi.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/api/PrivateApi.js b/javascript/src/api/PrivateApi.js index 20da24f..661f8a8 100644 --- a/javascript/src/api/PrivateApi.js +++ b/javascript/src/api/PrivateApi.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/api/PublicApi.js b/javascript/src/api/PublicApi.js index b33283f..a44e420 100644 --- a/javascript/src/api/PublicApi.js +++ b/javascript/src/api/PublicApi.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/api/SupportingApi.js b/javascript/src/api/SupportingApi.js index 6583a62..c37d39d 100644 --- a/javascript/src/api/SupportingApi.js +++ b/javascript/src/api/SupportingApi.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/api/TradingApi.js b/javascript/src/api/TradingApi.js index ce8c6d1..7c39e5d 100644 --- a/javascript/src/api/TradingApi.js +++ b/javascript/src/api/TradingApi.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/api/WalletApi.js b/javascript/src/api/WalletApi.js index 517f140..7cc9771 100644 --- a/javascript/src/api/WalletApi.js +++ b/javascript/src/api/WalletApi.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/index.js b/javascript/src/index.js index 95f68bd..ed375f4 100644 --- a/javascript/src/index.js +++ b/javascript/src/index.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/model/AddressBookItem.js b/javascript/src/model/AddressBookItem.js index cb00d22..2a1628e 100644 --- a/javascript/src/model/AddressBookItem.js +++ b/javascript/src/model/AddressBookItem.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/model/BookSummary.js b/javascript/src/model/BookSummary.js index c468e95..673a640 100644 --- a/javascript/src/model/BookSummary.js +++ b/javascript/src/model/BookSummary.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/model/Currency.js b/javascript/src/model/Currency.js index 1ff578e..dcb9e2d 100644 --- a/javascript/src/model/Currency.js +++ b/javascript/src/model/Currency.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/model/CurrencyPortfolio.js b/javascript/src/model/CurrencyPortfolio.js index b3a6b5c..cc08348 100644 --- a/javascript/src/model/CurrencyPortfolio.js +++ b/javascript/src/model/CurrencyPortfolio.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/model/CurrencyWithdrawalPriorities.js b/javascript/src/model/CurrencyWithdrawalPriorities.js index bf6523a..bc72735 100644 --- a/javascript/src/model/CurrencyWithdrawalPriorities.js +++ b/javascript/src/model/CurrencyWithdrawalPriorities.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/model/Deposit.js b/javascript/src/model/Deposit.js index c07c4a5..6fbf31c 100644 --- a/javascript/src/model/Deposit.js +++ b/javascript/src/model/Deposit.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/model/Instrument.js b/javascript/src/model/Instrument.js index ce580e2..36a552d 100644 --- a/javascript/src/model/Instrument.js +++ b/javascript/src/model/Instrument.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/model/KeyNumberPair.js b/javascript/src/model/KeyNumberPair.js index 4a7812d..81ec230 100644 --- a/javascript/src/model/KeyNumberPair.js +++ b/javascript/src/model/KeyNumberPair.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/model/Order.js b/javascript/src/model/Order.js index eb8376e..6db4a1e 100644 --- a/javascript/src/model/Order.js +++ b/javascript/src/model/Order.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/model/OrderIdInitialMarginPair.js b/javascript/src/model/OrderIdInitialMarginPair.js index caf279b..1d319f9 100644 --- a/javascript/src/model/OrderIdInitialMarginPair.js +++ b/javascript/src/model/OrderIdInitialMarginPair.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/model/Portfolio.js b/javascript/src/model/Portfolio.js index 09b5894..355c0ec 100644 --- a/javascript/src/model/Portfolio.js +++ b/javascript/src/model/Portfolio.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/model/PortfolioEth.js b/javascript/src/model/PortfolioEth.js index 4706ab9..798d74d 100644 --- a/javascript/src/model/PortfolioEth.js +++ b/javascript/src/model/PortfolioEth.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/model/Position.js b/javascript/src/model/Position.js index 4a518c1..1f2347d 100644 --- a/javascript/src/model/Position.js +++ b/javascript/src/model/Position.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/model/PublicTrade.js b/javascript/src/model/PublicTrade.js index 771ec3e..5a6a1d2 100644 --- a/javascript/src/model/PublicTrade.js +++ b/javascript/src/model/PublicTrade.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/model/Settlement.js b/javascript/src/model/Settlement.js index 3e520a5..95321c1 100644 --- a/javascript/src/model/Settlement.js +++ b/javascript/src/model/Settlement.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/model/TradesVolumes.js b/javascript/src/model/TradesVolumes.js index 4f4bc17..18530f7 100644 --- a/javascript/src/model/TradesVolumes.js +++ b/javascript/src/model/TradesVolumes.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/model/TransferItem.js b/javascript/src/model/TransferItem.js index 52b00c8..4751c09 100644 --- a/javascript/src/model/TransferItem.js +++ b/javascript/src/model/TransferItem.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/model/Types.js b/javascript/src/model/Types.js index 82e5df2..8dfcfe8 100644 --- a/javascript/src/model/Types.js +++ b/javascript/src/model/Types.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/model/UserTrade.js b/javascript/src/model/UserTrade.js index bd2cbf9..3580061 100644 --- a/javascript/src/model/UserTrade.js +++ b/javascript/src/model/UserTrade.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/javascript/src/model/Withdrawal.js b/javascript/src/model/Withdrawal.js index 58b9a96..2af5e10 100644 --- a/javascript/src/model/Withdrawal.js +++ b/javascript/src/model/Withdrawal.js @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/kotlin/.openapi-generator/VERSION b/kotlin/.openapi-generator/VERSION index afa6365..d96260b 100644 --- a/kotlin/.openapi-generator/VERSION +++ b/kotlin/.openapi-generator/VERSION @@ -1 +1 @@ -4.0.0-SNAPSHOT \ No newline at end of file +4.0.2-SNAPSHOT \ No newline at end of file diff --git a/kotlin/README.md b/kotlin/README.md index 5af1765..671da2a 100644 --- a/kotlin/README.md +++ b/kotlin/README.md @@ -2,7 +2,7 @@ ## Requires -* Kotlin 1.3.20 +* Kotlin 1.3.31 * Gradle 4.9 ## Build diff --git a/kotlin/build.gradle b/kotlin/build.gradle index 669d940..2f5e364 100644 --- a/kotlin/build.gradle +++ b/kotlin/build.gradle @@ -7,7 +7,7 @@ wrapper { } buildscript { - ext.kotlin_version = '1.3.20' + ext.kotlin_version = '1.3.31' repositories { mavenCentral() @@ -30,9 +30,8 @@ test { dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" - compile "com.squareup.moshi:moshi-kotlin:1.5.0" - compile "com.squareup.moshi:moshi-adapters:1.5.0" - compile "com.squareup.okhttp3:okhttp:3.8.0" - compile "org.threeten:threetenbp:1.3.6" + compile "com.squareup.moshi:moshi-kotlin:1.8.0" + compile "com.squareup.moshi:moshi-adapters:1.8.0" + compile "com.squareup.okhttp3:okhttp:3.14.2" testImplementation "io.kotlintest:kotlintest-runner-junit5:3.1.0" } diff --git a/kotlin/src/main/kotlin/org/openapitools/client/apis/AccountManagementApi.kt b/kotlin/src/main/kotlin/org/openapitools/client/apis/AccountManagementApi.kt index bf61860..5a94f0d 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/apis/AccountManagementApi.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/apis/AccountManagementApi.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -12,7 +12,17 @@ package org.openapitools.client.apis -import org.openapitools.client.infrastructure.* +import org.openapitools.client.infrastructure.ApiClient +import org.openapitools.client.infrastructure.ClientException +import org.openapitools.client.infrastructure.ClientError +import org.openapitools.client.infrastructure.ServerException +import org.openapitools.client.infrastructure.ServerError +import org.openapitools.client.infrastructure.MultiValueMap +import org.openapitools.client.infrastructure.RequestConfig +import org.openapitools.client.infrastructure.RequestMethod +import org.openapitools.client.infrastructure.ResponseType +import org.openapitools.client.infrastructure.Success +import org.openapitools.client.infrastructure.toMultiValue class AccountManagementApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : ApiClient(basePath) { @@ -27,7 +37,7 @@ class AccountManagementApi(basePath: kotlin.String = "https://www.deribit.com/ap fun privateChangeSubaccountNameGet(sid: kotlin.Int, name: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("sid" to listOf("$sid"), "name" to listOf("$name")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/change_subaccount_name", @@ -57,7 +67,7 @@ class AccountManagementApi(basePath: kotlin.String = "https://www.deribit.com/ap fun privateCreateSubaccountGet() : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf() - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/create_subaccount", @@ -88,7 +98,7 @@ class AccountManagementApi(basePath: kotlin.String = "https://www.deribit.com/ap fun privateDisableTfaForSubaccountGet(sid: kotlin.Int) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("sid" to listOf("$sid")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/disable_tfa_for_subaccount", @@ -120,7 +130,7 @@ class AccountManagementApi(basePath: kotlin.String = "https://www.deribit.com/ap fun privateGetAccountSummaryGet(currency: kotlin.String, extended: kotlin.Boolean?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "extended" to listOf("$extended")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_account_summary", @@ -150,7 +160,7 @@ class AccountManagementApi(basePath: kotlin.String = "https://www.deribit.com/ap fun privateGetEmailLanguageGet() : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf() - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_email_language", @@ -180,7 +190,7 @@ class AccountManagementApi(basePath: kotlin.String = "https://www.deribit.com/ap fun privateGetNewAnnouncementsGet() : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf() - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_new_announcements", @@ -211,7 +221,7 @@ class AccountManagementApi(basePath: kotlin.String = "https://www.deribit.com/ap fun privateGetPositionGet(instrumentName: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_position", @@ -243,7 +253,7 @@ class AccountManagementApi(basePath: kotlin.String = "https://www.deribit.com/ap fun privateGetPositionsGet(currency: kotlin.String, kind: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "kind" to listOf("$kind")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_positions", @@ -274,7 +284,7 @@ class AccountManagementApi(basePath: kotlin.String = "https://www.deribit.com/ap fun privateGetSubaccountsGet(withPortfolio: kotlin.Boolean?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("withPortfolio" to listOf("$withPortfolio")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_subaccounts", @@ -305,7 +315,7 @@ class AccountManagementApi(basePath: kotlin.String = "https://www.deribit.com/ap fun privateSetAnnouncementAsReadGet(announcementId: java.math.BigDecimal) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("announcementId" to listOf("$announcementId")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/set_announcement_as_read", @@ -337,7 +347,7 @@ class AccountManagementApi(basePath: kotlin.String = "https://www.deribit.com/ap fun privateSetEmailForSubaccountGet(sid: kotlin.Int, email: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("sid" to listOf("$sid"), "email" to listOf("$email")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/set_email_for_subaccount", @@ -368,7 +378,7 @@ class AccountManagementApi(basePath: kotlin.String = "https://www.deribit.com/ap fun privateSetEmailLanguageGet(language: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("language" to listOf("$language")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/set_email_language", @@ -400,7 +410,7 @@ class AccountManagementApi(basePath: kotlin.String = "https://www.deribit.com/ap fun privateSetPasswordForSubaccountGet(sid: kotlin.Int, password: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("sid" to listOf("$sid"), "password" to listOf("$password")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/set_password_for_subaccount", @@ -432,7 +442,7 @@ class AccountManagementApi(basePath: kotlin.String = "https://www.deribit.com/ap fun privateToggleNotificationsFromSubaccountGet(sid: kotlin.Int, state: kotlin.Boolean) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("sid" to listOf("$sid"), "state" to listOf("$state")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/toggle_notifications_from_subaccount", @@ -464,7 +474,7 @@ class AccountManagementApi(basePath: kotlin.String = "https://www.deribit.com/ap fun privateToggleSubaccountLoginGet(sid: kotlin.Int, state: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("sid" to listOf("$sid"), "state" to listOf("$state")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/toggle_subaccount_login", @@ -494,7 +504,7 @@ class AccountManagementApi(basePath: kotlin.String = "https://www.deribit.com/ap fun publicGetAnnouncementsGet() : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf() - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_announcements", diff --git a/kotlin/src/main/kotlin/org/openapitools/client/apis/AuthenticationApi.kt b/kotlin/src/main/kotlin/org/openapitools/client/apis/AuthenticationApi.kt index 8a863ba..2f957a2 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/apis/AuthenticationApi.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/apis/AuthenticationApi.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -12,7 +12,17 @@ package org.openapitools.client.apis -import org.openapitools.client.infrastructure.* +import org.openapitools.client.infrastructure.ApiClient +import org.openapitools.client.infrastructure.ClientException +import org.openapitools.client.infrastructure.ClientError +import org.openapitools.client.infrastructure.ServerException +import org.openapitools.client.infrastructure.ServerError +import org.openapitools.client.infrastructure.MultiValueMap +import org.openapitools.client.infrastructure.RequestConfig +import org.openapitools.client.infrastructure.RequestMethod +import org.openapitools.client.infrastructure.ResponseType +import org.openapitools.client.infrastructure.Success +import org.openapitools.client.infrastructure.toMultiValue class AuthenticationApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : ApiClient(basePath) { @@ -36,7 +46,7 @@ class AuthenticationApi(basePath: kotlin.String = "https://www.deribit.com/api/v fun publicAuthGet(grantType: kotlin.String, username: kotlin.String, password: kotlin.String, clientId: kotlin.String, clientSecret: kotlin.String, refreshToken: kotlin.String, timestamp: kotlin.String, signature: kotlin.String, nonce: kotlin.String?, state: kotlin.String?, scope: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("grantType" to listOf("$grantType"), "username" to listOf("$username"), "password" to listOf("$password"), "clientId" to listOf("$clientId"), "clientSecret" to listOf("$clientSecret"), "refreshToken" to listOf("$refreshToken"), "timestamp" to listOf("$timestamp"), "signature" to listOf("$signature"), "nonce" to listOf("$nonce"), "state" to listOf("$state"), "scope" to listOf("$scope")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/auth", diff --git a/kotlin/src/main/kotlin/org/openapitools/client/apis/InternalApi.kt b/kotlin/src/main/kotlin/org/openapitools/client/apis/InternalApi.kt index 26d4c76..8642fd8 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/apis/InternalApi.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/apis/InternalApi.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -12,7 +12,17 @@ package org.openapitools.client.apis -import org.openapitools.client.infrastructure.* +import org.openapitools.client.infrastructure.ApiClient +import org.openapitools.client.infrastructure.ClientException +import org.openapitools.client.infrastructure.ClientError +import org.openapitools.client.infrastructure.ServerException +import org.openapitools.client.infrastructure.ServerError +import org.openapitools.client.infrastructure.MultiValueMap +import org.openapitools.client.infrastructure.RequestConfig +import org.openapitools.client.infrastructure.RequestMethod +import org.openapitools.client.infrastructure.ResponseType +import org.openapitools.client.infrastructure.Success +import org.openapitools.client.infrastructure.toMultiValue class InternalApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : ApiClient(basePath) { @@ -30,7 +40,7 @@ class InternalApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : fun privateAddToAddressBookGet(currency: kotlin.String, type: kotlin.String, address: kotlin.String, name: kotlin.String, tfa: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "type" to listOf("$type"), "address" to listOf("$address"), "name" to listOf("$name"), "tfa" to listOf("$tfa")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/add_to_address_book", @@ -62,7 +72,7 @@ class InternalApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : fun privateDisableTfaWithRecoveryCodeGet(password: kotlin.String, code: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("password" to listOf("$password"), "code" to listOf("$code")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/disable_tfa_with_recovery_code", @@ -94,7 +104,7 @@ class InternalApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : fun privateGetAddressBookGet(currency: kotlin.String, type: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "type" to listOf("$type")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_address_book", @@ -128,7 +138,7 @@ class InternalApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : fun privateRemoveFromAddressBookGet(currency: kotlin.String, type: kotlin.String, address: kotlin.String, tfa: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "type" to listOf("$type"), "address" to listOf("$address"), "tfa" to listOf("$tfa")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/remove_from_address_book", @@ -161,7 +171,7 @@ class InternalApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : fun privateSubmitTransferToSubaccountGet(currency: kotlin.String, amount: java.math.BigDecimal, destination: kotlin.Int) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "amount" to listOf("$amount"), "destination" to listOf("$destination")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/submit_transfer_to_subaccount", @@ -195,7 +205,7 @@ class InternalApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : fun privateSubmitTransferToUserGet(currency: kotlin.String, amount: java.math.BigDecimal, destination: kotlin.String, tfa: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "amount" to listOf("$amount"), "destination" to listOf("$destination"), "tfa" to listOf("$tfa")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/submit_transfer_to_user", @@ -227,7 +237,7 @@ class InternalApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : fun privateToggleDepositAddressCreationGet(currency: kotlin.String, state: kotlin.Boolean) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "state" to listOf("$state")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/toggle_deposit_address_creation", @@ -257,7 +267,7 @@ class InternalApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : fun publicGetFooterGet() : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf() - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_footer", @@ -288,7 +298,7 @@ class InternalApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : fun publicGetOptionMarkPricesGet(currency: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_option_mark_prices", @@ -321,7 +331,7 @@ class InternalApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : fun publicValidateFieldGet(field: kotlin.String, value: kotlin.String, value2: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("field" to listOf("$field"), "value" to listOf("$value"), "value2" to listOf("$value2")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/validate_field", diff --git a/kotlin/src/main/kotlin/org/openapitools/client/apis/MarketDataApi.kt b/kotlin/src/main/kotlin/org/openapitools/client/apis/MarketDataApi.kt index 4702483..43dcbf5 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/apis/MarketDataApi.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/apis/MarketDataApi.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -12,7 +12,17 @@ package org.openapitools.client.apis -import org.openapitools.client.infrastructure.* +import org.openapitools.client.infrastructure.ApiClient +import org.openapitools.client.infrastructure.ClientException +import org.openapitools.client.infrastructure.ClientError +import org.openapitools.client.infrastructure.ServerException +import org.openapitools.client.infrastructure.ServerError +import org.openapitools.client.infrastructure.MultiValueMap +import org.openapitools.client.infrastructure.RequestConfig +import org.openapitools.client.infrastructure.RequestMethod +import org.openapitools.client.infrastructure.ResponseType +import org.openapitools.client.infrastructure.Success +import org.openapitools.client.infrastructure.toMultiValue class MarketDataApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : ApiClient(basePath) { @@ -27,7 +37,7 @@ class MarketDataApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") fun publicGetBookSummaryByCurrencyGet(currency: kotlin.String, kind: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "kind" to listOf("$kind")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_book_summary_by_currency", @@ -58,7 +68,7 @@ class MarketDataApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") fun publicGetBookSummaryByInstrumentGet(instrumentName: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_book_summary_by_instrument", @@ -89,7 +99,7 @@ class MarketDataApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") fun publicGetContractSizeGet(instrumentName: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_contract_size", @@ -119,7 +129,7 @@ class MarketDataApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") fun publicGetCurrenciesGet() : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf() - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_currencies", @@ -151,7 +161,7 @@ class MarketDataApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") fun publicGetFundingChartDataGet(instrumentName: kotlin.String, length: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "length" to listOf("$length")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_funding_chart_data", @@ -182,7 +192,7 @@ class MarketDataApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") fun publicGetHistoricalVolatilityGet(currency: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_historical_volatility", @@ -213,7 +223,7 @@ class MarketDataApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") fun publicGetIndexGet(currency: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_index", @@ -246,7 +256,7 @@ class MarketDataApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") fun publicGetInstrumentsGet(currency: kotlin.String, kind: kotlin.String?, expired: kotlin.Boolean?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "kind" to listOf("$kind"), "expired" to listOf("$expired")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_instruments", @@ -281,7 +291,7 @@ class MarketDataApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") fun publicGetLastSettlementsByCurrencyGet(currency: kotlin.String, type: kotlin.String?, count: kotlin.Int?, continuation: kotlin.String?, searchStartTimestamp: kotlin.Int?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "type" to listOf("$type"), "count" to listOf("$count"), "continuation" to listOf("$continuation"), "searchStartTimestamp" to listOf("$searchStartTimestamp")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_last_settlements_by_currency", @@ -316,7 +326,7 @@ class MarketDataApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") fun publicGetLastSettlementsByInstrumentGet(instrumentName: kotlin.String, type: kotlin.String?, count: kotlin.Int?, continuation: kotlin.String?, searchStartTimestamp: kotlin.Int?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "type" to listOf("$type"), "count" to listOf("$count"), "continuation" to listOf("$continuation"), "searchStartTimestamp" to listOf("$searchStartTimestamp")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_last_settlements_by_instrument", @@ -353,7 +363,7 @@ class MarketDataApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") fun publicGetLastTradesByCurrencyAndTimeGet(currency: kotlin.String, startTimestamp: kotlin.Int, endTimestamp: kotlin.Int, kind: kotlin.String?, count: kotlin.Int?, includeOld: kotlin.Boolean?, sorting: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "kind" to listOf("$kind"), "startTimestamp" to listOf("$startTimestamp"), "endTimestamp" to listOf("$endTimestamp"), "count" to listOf("$count"), "includeOld" to listOf("$includeOld"), "sorting" to listOf("$sorting")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_last_trades_by_currency_and_time", @@ -390,7 +400,7 @@ class MarketDataApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") fun publicGetLastTradesByCurrencyGet(currency: kotlin.String, kind: kotlin.String?, startId: kotlin.String?, endId: kotlin.String?, count: kotlin.Int?, includeOld: kotlin.Boolean?, sorting: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "kind" to listOf("$kind"), "startId" to listOf("$startId"), "endId" to listOf("$endId"), "count" to listOf("$count"), "includeOld" to listOf("$includeOld"), "sorting" to listOf("$sorting")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_last_trades_by_currency", @@ -426,7 +436,7 @@ class MarketDataApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") fun publicGetLastTradesByInstrumentAndTimeGet(instrumentName: kotlin.String, startTimestamp: kotlin.Int, endTimestamp: kotlin.Int, count: kotlin.Int?, includeOld: kotlin.Boolean?, sorting: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "startTimestamp" to listOf("$startTimestamp"), "endTimestamp" to listOf("$endTimestamp"), "count" to listOf("$count"), "includeOld" to listOf("$includeOld"), "sorting" to listOf("$sorting")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_last_trades_by_instrument_and_time", @@ -462,7 +472,7 @@ class MarketDataApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") fun publicGetLastTradesByInstrumentGet(instrumentName: kotlin.String, startSeq: kotlin.Int?, endSeq: kotlin.Int?, count: kotlin.Int?, includeOld: kotlin.Boolean?, sorting: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "startSeq" to listOf("$startSeq"), "endSeq" to listOf("$endSeq"), "count" to listOf("$count"), "includeOld" to listOf("$includeOld"), "sorting" to listOf("$sorting")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_last_trades_by_instrument", @@ -494,7 +504,7 @@ class MarketDataApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") fun publicGetOrderBookGet(instrumentName: kotlin.String, depth: java.math.BigDecimal?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "depth" to listOf("$depth")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_order_book", @@ -524,7 +534,7 @@ class MarketDataApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") fun publicGetTradeVolumesGet() : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf() - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_trade_volumes", @@ -557,7 +567,7 @@ class MarketDataApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") fun publicGetTradingviewChartDataGet(instrumentName: kotlin.String, startTimestamp: kotlin.Int, endTimestamp: kotlin.Int) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "startTimestamp" to listOf("$startTimestamp"), "endTimestamp" to listOf("$endTimestamp")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_tradingview_chart_data", @@ -588,7 +598,7 @@ class MarketDataApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") fun publicTickerGet(instrumentName: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/ticker", diff --git a/kotlin/src/main/kotlin/org/openapitools/client/apis/PrivateApi.kt b/kotlin/src/main/kotlin/org/openapitools/client/apis/PrivateApi.kt index ecbe29f..af2c16a 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/apis/PrivateApi.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/apis/PrivateApi.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -12,7 +12,17 @@ package org.openapitools.client.apis -import org.openapitools.client.infrastructure.* +import org.openapitools.client.infrastructure.ApiClient +import org.openapitools.client.infrastructure.ClientException +import org.openapitools.client.infrastructure.ClientError +import org.openapitools.client.infrastructure.ServerException +import org.openapitools.client.infrastructure.ServerError +import org.openapitools.client.infrastructure.MultiValueMap +import org.openapitools.client.infrastructure.RequestConfig +import org.openapitools.client.infrastructure.RequestMethod +import org.openapitools.client.infrastructure.ResponseType +import org.openapitools.client.infrastructure.Success +import org.openapitools.client.infrastructure.toMultiValue class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : ApiClient(basePath) { @@ -30,7 +40,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateAddToAddressBookGet(currency: kotlin.String, type: kotlin.String, address: kotlin.String, name: kotlin.String, tfa: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "type" to listOf("$type"), "address" to listOf("$address"), "name" to listOf("$name"), "tfa" to listOf("$tfa")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/add_to_address_book", @@ -72,7 +82,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateBuyGet(instrumentName: kotlin.String, amount: java.math.BigDecimal, type: kotlin.String?, label: kotlin.String?, price: java.math.BigDecimal?, timeInForce: kotlin.String?, maxShow: java.math.BigDecimal?, postOnly: kotlin.Boolean?, reduceOnly: kotlin.Boolean?, stopPrice: java.math.BigDecimal?, trigger: kotlin.String?, advanced: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "amount" to listOf("$amount"), "type" to listOf("$type"), "label" to listOf("$label"), "price" to listOf("$price"), "timeInForce" to listOf("$timeInForce"), "maxShow" to listOf("$maxShow"), "postOnly" to listOf("$postOnly"), "reduceOnly" to listOf("$reduceOnly"), "stopPrice" to listOf("$stopPrice"), "trigger" to listOf("$trigger"), "advanced" to listOf("$advanced")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/buy", @@ -105,7 +115,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateCancelAllByCurrencyGet(currency: kotlin.String, kind: kotlin.String?, type: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "kind" to listOf("$kind"), "type" to listOf("$type")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/cancel_all_by_currency", @@ -137,7 +147,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateCancelAllByInstrumentGet(instrumentName: kotlin.String, type: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "type" to listOf("$type")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/cancel_all_by_instrument", @@ -167,7 +177,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateCancelAllGet() : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf() - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/cancel_all", @@ -198,7 +208,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateCancelGet(orderId: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("orderId" to listOf("$orderId")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/cancel", @@ -231,7 +241,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateCancelTransferByIdGet(currency: kotlin.String, id: kotlin.Int, tfa: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "id" to listOf("$id"), "tfa" to listOf("$tfa")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/cancel_transfer_by_id", @@ -263,7 +273,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateCancelWithdrawalGet(currency: kotlin.String, id: java.math.BigDecimal) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "id" to listOf("$id")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/cancel_withdrawal", @@ -295,7 +305,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateChangeSubaccountNameGet(sid: kotlin.Int, name: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("sid" to listOf("$sid"), "name" to listOf("$name")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/change_subaccount_name", @@ -328,7 +338,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateClosePositionGet(instrumentName: kotlin.String, type: kotlin.String, price: java.math.BigDecimal?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "type" to listOf("$type"), "price" to listOf("$price")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/close_position", @@ -359,7 +369,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateCreateDepositAddressGet(currency: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/create_deposit_address", @@ -389,7 +399,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateCreateSubaccountGet() : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf() - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/create_subaccount", @@ -420,7 +430,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateDisableTfaForSubaccountGet(sid: kotlin.Int) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("sid" to listOf("$sid")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/disable_tfa_for_subaccount", @@ -452,7 +462,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateDisableTfaWithRecoveryCodeGet(password: kotlin.String, code: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("password" to listOf("$password"), "code" to listOf("$code")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/disable_tfa_with_recovery_code", @@ -488,7 +498,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateEditGet(orderId: kotlin.String, amount: java.math.BigDecimal, price: java.math.BigDecimal, postOnly: kotlin.Boolean?, advanced: kotlin.String?, stopPrice: java.math.BigDecimal?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("orderId" to listOf("$orderId"), "amount" to listOf("$amount"), "price" to listOf("$price"), "postOnly" to listOf("$postOnly"), "advanced" to listOf("$advanced"), "stopPrice" to listOf("$stopPrice")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/edit", @@ -520,7 +530,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetAccountSummaryGet(currency: kotlin.String, extended: kotlin.Boolean?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "extended" to listOf("$extended")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_account_summary", @@ -552,7 +562,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetAddressBookGet(currency: kotlin.String, type: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "type" to listOf("$type")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_address_book", @@ -583,7 +593,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetCurrentDepositAddressGet(currency: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_current_deposit_address", @@ -616,7 +626,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetDepositsGet(currency: kotlin.String, count: kotlin.Int?, offset: kotlin.Int?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "count" to listOf("$count"), "offset" to listOf("$offset")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_deposits", @@ -646,7 +656,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetEmailLanguageGet() : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf() - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_email_language", @@ -679,7 +689,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetMarginsGet(instrumentName: kotlin.String, amount: java.math.BigDecimal, price: java.math.BigDecimal) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "amount" to listOf("$amount"), "price" to listOf("$price")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_margins", @@ -709,7 +719,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetNewAnnouncementsGet() : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf() - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_new_announcements", @@ -742,7 +752,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetOpenOrdersByCurrencyGet(currency: kotlin.String, kind: kotlin.String?, type: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "kind" to listOf("$kind"), "type" to listOf("$type")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_open_orders_by_currency", @@ -774,7 +784,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetOpenOrdersByInstrumentGet(instrumentName: kotlin.String, type: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "type" to listOf("$type")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_open_orders_by_instrument", @@ -810,7 +820,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetOrderHistoryByCurrencyGet(currency: kotlin.String, kind: kotlin.String?, count: kotlin.Int?, offset: kotlin.Int?, includeOld: kotlin.Boolean?, includeUnfilled: kotlin.Boolean?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "kind" to listOf("$kind"), "count" to listOf("$count"), "offset" to listOf("$offset"), "includeOld" to listOf("$includeOld"), "includeUnfilled" to listOf("$includeUnfilled")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_order_history_by_currency", @@ -845,7 +855,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetOrderHistoryByInstrumentGet(instrumentName: kotlin.String, count: kotlin.Int?, offset: kotlin.Int?, includeOld: kotlin.Boolean?, includeUnfilled: kotlin.Boolean?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "count" to listOf("$count"), "offset" to listOf("$offset"), "includeOld" to listOf("$includeOld"), "includeUnfilled" to listOf("$includeUnfilled")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_order_history_by_instrument", @@ -876,7 +886,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetOrderMarginByIdsGet(ids: kotlin.Array) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("ids" to toMultiValue(ids.toList(), "multi")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_order_margin_by_ids", @@ -907,7 +917,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetOrderStateGet(orderId: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("orderId" to listOf("$orderId")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_order_state", @@ -938,7 +948,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetPositionGet(instrumentName: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_position", @@ -970,7 +980,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetPositionsGet(currency: kotlin.String, kind: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "kind" to listOf("$kind")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_positions", @@ -1003,7 +1013,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetSettlementHistoryByCurrencyGet(currency: kotlin.String, type: kotlin.String?, count: kotlin.Int?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "type" to listOf("$type"), "count" to listOf("$count")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_settlement_history_by_currency", @@ -1036,7 +1046,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetSettlementHistoryByInstrumentGet(instrumentName: kotlin.String, type: kotlin.String?, count: kotlin.Int?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "type" to listOf("$type"), "count" to listOf("$count")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_settlement_history_by_instrument", @@ -1067,7 +1077,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetSubaccountsGet(withPortfolio: kotlin.Boolean?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("withPortfolio" to listOf("$withPortfolio")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_subaccounts", @@ -1100,7 +1110,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetTransfersGet(currency: kotlin.String, count: kotlin.Int?, offset: kotlin.Int?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "count" to listOf("$count"), "offset" to listOf("$offset")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_transfers", @@ -1137,7 +1147,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetUserTradesByCurrencyAndTimeGet(currency: kotlin.String, startTimestamp: kotlin.Int, endTimestamp: kotlin.Int, kind: kotlin.String?, count: kotlin.Int?, includeOld: kotlin.Boolean?, sorting: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "kind" to listOf("$kind"), "startTimestamp" to listOf("$startTimestamp"), "endTimestamp" to listOf("$endTimestamp"), "count" to listOf("$count"), "includeOld" to listOf("$includeOld"), "sorting" to listOf("$sorting")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_user_trades_by_currency_and_time", @@ -1174,7 +1184,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetUserTradesByCurrencyGet(currency: kotlin.String, kind: kotlin.String?, startId: kotlin.String?, endId: kotlin.String?, count: kotlin.Int?, includeOld: kotlin.Boolean?, sorting: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "kind" to listOf("$kind"), "startId" to listOf("$startId"), "endId" to listOf("$endId"), "count" to listOf("$count"), "includeOld" to listOf("$includeOld"), "sorting" to listOf("$sorting")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_user_trades_by_currency", @@ -1210,7 +1220,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetUserTradesByInstrumentAndTimeGet(instrumentName: kotlin.String, startTimestamp: kotlin.Int, endTimestamp: kotlin.Int, count: kotlin.Int?, includeOld: kotlin.Boolean?, sorting: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "startTimestamp" to listOf("$startTimestamp"), "endTimestamp" to listOf("$endTimestamp"), "count" to listOf("$count"), "includeOld" to listOf("$includeOld"), "sorting" to listOf("$sorting")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_user_trades_by_instrument_and_time", @@ -1246,7 +1256,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetUserTradesByInstrumentGet(instrumentName: kotlin.String, startSeq: kotlin.Int?, endSeq: kotlin.Int?, count: kotlin.Int?, includeOld: kotlin.Boolean?, sorting: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "startSeq" to listOf("$startSeq"), "endSeq" to listOf("$endSeq"), "count" to listOf("$count"), "includeOld" to listOf("$includeOld"), "sorting" to listOf("$sorting")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_user_trades_by_instrument", @@ -1278,7 +1288,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetUserTradesByOrderGet(orderId: kotlin.String, sorting: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("orderId" to listOf("$orderId"), "sorting" to listOf("$sorting")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_user_trades_by_order", @@ -1311,7 +1321,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetWithdrawalsGet(currency: kotlin.String, count: kotlin.Int?, offset: kotlin.Int?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "count" to listOf("$count"), "offset" to listOf("$offset")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_withdrawals", @@ -1345,7 +1355,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateRemoveFromAddressBookGet(currency: kotlin.String, type: kotlin.String, address: kotlin.String, tfa: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "type" to listOf("$type"), "address" to listOf("$address"), "tfa" to listOf("$tfa")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/remove_from_address_book", @@ -1387,7 +1397,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateSellGet(instrumentName: kotlin.String, amount: java.math.BigDecimal, type: kotlin.String?, label: kotlin.String?, price: java.math.BigDecimal?, timeInForce: kotlin.String?, maxShow: java.math.BigDecimal?, postOnly: kotlin.Boolean?, reduceOnly: kotlin.Boolean?, stopPrice: java.math.BigDecimal?, trigger: kotlin.String?, advanced: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "amount" to listOf("$amount"), "type" to listOf("$type"), "label" to listOf("$label"), "price" to listOf("$price"), "timeInForce" to listOf("$timeInForce"), "maxShow" to listOf("$maxShow"), "postOnly" to listOf("$postOnly"), "reduceOnly" to listOf("$reduceOnly"), "stopPrice" to listOf("$stopPrice"), "trigger" to listOf("$trigger"), "advanced" to listOf("$advanced")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/sell", @@ -1418,7 +1428,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateSetAnnouncementAsReadGet(announcementId: java.math.BigDecimal) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("announcementId" to listOf("$announcementId")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/set_announcement_as_read", @@ -1450,7 +1460,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateSetEmailForSubaccountGet(sid: kotlin.Int, email: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("sid" to listOf("$sid"), "email" to listOf("$email")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/set_email_for_subaccount", @@ -1481,7 +1491,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateSetEmailLanguageGet(language: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("language" to listOf("$language")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/set_email_language", @@ -1513,7 +1523,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateSetPasswordForSubaccountGet(sid: kotlin.Int, password: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("sid" to listOf("$sid"), "password" to listOf("$password")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/set_password_for_subaccount", @@ -1546,7 +1556,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateSubmitTransferToSubaccountGet(currency: kotlin.String, amount: java.math.BigDecimal, destination: kotlin.Int) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "amount" to listOf("$amount"), "destination" to listOf("$destination")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/submit_transfer_to_subaccount", @@ -1580,7 +1590,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateSubmitTransferToUserGet(currency: kotlin.String, amount: java.math.BigDecimal, destination: kotlin.String, tfa: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "amount" to listOf("$amount"), "destination" to listOf("$destination"), "tfa" to listOf("$tfa")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/submit_transfer_to_user", @@ -1612,7 +1622,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateToggleDepositAddressCreationGet(currency: kotlin.String, state: kotlin.Boolean) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "state" to listOf("$state")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/toggle_deposit_address_creation", @@ -1644,7 +1654,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateToggleNotificationsFromSubaccountGet(sid: kotlin.Int, state: kotlin.Boolean) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("sid" to listOf("$sid"), "state" to listOf("$state")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/toggle_notifications_from_subaccount", @@ -1676,7 +1686,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateToggleSubaccountLoginGet(sid: kotlin.Int, state: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("sid" to listOf("$sid"), "state" to listOf("$state")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/toggle_subaccount_login", @@ -1711,7 +1721,7 @@ class PrivateApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateWithdrawGet(currency: kotlin.String, address: kotlin.String, amount: java.math.BigDecimal, priority: kotlin.String?, tfa: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "address" to listOf("$address"), "amount" to listOf("$amount"), "priority" to listOf("$priority"), "tfa" to listOf("$tfa")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/withdraw", diff --git a/kotlin/src/main/kotlin/org/openapitools/client/apis/PublicApi.kt b/kotlin/src/main/kotlin/org/openapitools/client/apis/PublicApi.kt index 84b3cfb..36845eb 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/apis/PublicApi.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/apis/PublicApi.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -12,7 +12,17 @@ package org.openapitools.client.apis -import org.openapitools.client.infrastructure.* +import org.openapitools.client.infrastructure.ApiClient +import org.openapitools.client.infrastructure.ClientException +import org.openapitools.client.infrastructure.ClientError +import org.openapitools.client.infrastructure.ServerException +import org.openapitools.client.infrastructure.ServerError +import org.openapitools.client.infrastructure.MultiValueMap +import org.openapitools.client.infrastructure.RequestConfig +import org.openapitools.client.infrastructure.RequestMethod +import org.openapitools.client.infrastructure.ResponseType +import org.openapitools.client.infrastructure.Success +import org.openapitools.client.infrastructure.toMultiValue class PublicApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : ApiClient(basePath) { @@ -36,7 +46,7 @@ class PublicApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun publicAuthGet(grantType: kotlin.String, username: kotlin.String, password: kotlin.String, clientId: kotlin.String, clientSecret: kotlin.String, refreshToken: kotlin.String, timestamp: kotlin.String, signature: kotlin.String, nonce: kotlin.String?, state: kotlin.String?, scope: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("grantType" to listOf("$grantType"), "username" to listOf("$username"), "password" to listOf("$password"), "clientId" to listOf("$clientId"), "clientSecret" to listOf("$clientSecret"), "refreshToken" to listOf("$refreshToken"), "timestamp" to listOf("$timestamp"), "signature" to listOf("$signature"), "nonce" to listOf("$nonce"), "state" to listOf("$state"), "scope" to listOf("$scope")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/auth", @@ -66,7 +76,7 @@ class PublicApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun publicGetAnnouncementsGet() : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf() - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_announcements", @@ -98,7 +108,7 @@ class PublicApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun publicGetBookSummaryByCurrencyGet(currency: kotlin.String, kind: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "kind" to listOf("$kind")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_book_summary_by_currency", @@ -129,7 +139,7 @@ class PublicApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun publicGetBookSummaryByInstrumentGet(instrumentName: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_book_summary_by_instrument", @@ -160,7 +170,7 @@ class PublicApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun publicGetContractSizeGet(instrumentName: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_contract_size", @@ -190,7 +200,7 @@ class PublicApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun publicGetCurrenciesGet() : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf() - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_currencies", @@ -222,7 +232,7 @@ class PublicApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun publicGetFundingChartDataGet(instrumentName: kotlin.String, length: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "length" to listOf("$length")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_funding_chart_data", @@ -253,7 +263,7 @@ class PublicApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun publicGetHistoricalVolatilityGet(currency: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_historical_volatility", @@ -284,7 +294,7 @@ class PublicApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun publicGetIndexGet(currency: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_index", @@ -317,7 +327,7 @@ class PublicApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun publicGetInstrumentsGet(currency: kotlin.String, kind: kotlin.String?, expired: kotlin.Boolean?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "kind" to listOf("$kind"), "expired" to listOf("$expired")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_instruments", @@ -352,7 +362,7 @@ class PublicApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun publicGetLastSettlementsByCurrencyGet(currency: kotlin.String, type: kotlin.String?, count: kotlin.Int?, continuation: kotlin.String?, searchStartTimestamp: kotlin.Int?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "type" to listOf("$type"), "count" to listOf("$count"), "continuation" to listOf("$continuation"), "searchStartTimestamp" to listOf("$searchStartTimestamp")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_last_settlements_by_currency", @@ -387,7 +397,7 @@ class PublicApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun publicGetLastSettlementsByInstrumentGet(instrumentName: kotlin.String, type: kotlin.String?, count: kotlin.Int?, continuation: kotlin.String?, searchStartTimestamp: kotlin.Int?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "type" to listOf("$type"), "count" to listOf("$count"), "continuation" to listOf("$continuation"), "searchStartTimestamp" to listOf("$searchStartTimestamp")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_last_settlements_by_instrument", @@ -424,7 +434,7 @@ class PublicApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun publicGetLastTradesByCurrencyAndTimeGet(currency: kotlin.String, startTimestamp: kotlin.Int, endTimestamp: kotlin.Int, kind: kotlin.String?, count: kotlin.Int?, includeOld: kotlin.Boolean?, sorting: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "kind" to listOf("$kind"), "startTimestamp" to listOf("$startTimestamp"), "endTimestamp" to listOf("$endTimestamp"), "count" to listOf("$count"), "includeOld" to listOf("$includeOld"), "sorting" to listOf("$sorting")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_last_trades_by_currency_and_time", @@ -461,7 +471,7 @@ class PublicApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun publicGetLastTradesByCurrencyGet(currency: kotlin.String, kind: kotlin.String?, startId: kotlin.String?, endId: kotlin.String?, count: kotlin.Int?, includeOld: kotlin.Boolean?, sorting: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "kind" to listOf("$kind"), "startId" to listOf("$startId"), "endId" to listOf("$endId"), "count" to listOf("$count"), "includeOld" to listOf("$includeOld"), "sorting" to listOf("$sorting")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_last_trades_by_currency", @@ -497,7 +507,7 @@ class PublicApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun publicGetLastTradesByInstrumentAndTimeGet(instrumentName: kotlin.String, startTimestamp: kotlin.Int, endTimestamp: kotlin.Int, count: kotlin.Int?, includeOld: kotlin.Boolean?, sorting: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "startTimestamp" to listOf("$startTimestamp"), "endTimestamp" to listOf("$endTimestamp"), "count" to listOf("$count"), "includeOld" to listOf("$includeOld"), "sorting" to listOf("$sorting")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_last_trades_by_instrument_and_time", @@ -533,7 +543,7 @@ class PublicApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun publicGetLastTradesByInstrumentGet(instrumentName: kotlin.String, startSeq: kotlin.Int?, endSeq: kotlin.Int?, count: kotlin.Int?, includeOld: kotlin.Boolean?, sorting: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "startSeq" to listOf("$startSeq"), "endSeq" to listOf("$endSeq"), "count" to listOf("$count"), "includeOld" to listOf("$includeOld"), "sorting" to listOf("$sorting")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_last_trades_by_instrument", @@ -565,7 +575,7 @@ class PublicApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun publicGetOrderBookGet(instrumentName: kotlin.String, depth: java.math.BigDecimal?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "depth" to listOf("$depth")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_order_book", @@ -595,7 +605,7 @@ class PublicApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun publicGetTimeGet() : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf() - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_time", @@ -625,7 +635,7 @@ class PublicApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun publicGetTradeVolumesGet() : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf() - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_trade_volumes", @@ -658,7 +668,7 @@ class PublicApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun publicGetTradingviewChartDataGet(instrumentName: kotlin.String, startTimestamp: kotlin.Int, endTimestamp: kotlin.Int) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "startTimestamp" to listOf("$startTimestamp"), "endTimestamp" to listOf("$endTimestamp")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_tradingview_chart_data", @@ -689,7 +699,7 @@ class PublicApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun publicTestGet(expectedResult: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("expectedResult" to listOf("$expectedResult")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/test", @@ -720,7 +730,7 @@ class PublicApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun publicTickerGet(instrumentName: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/ticker", @@ -753,7 +763,7 @@ class PublicApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun publicValidateFieldGet(field: kotlin.String, value: kotlin.String, value2: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("field" to listOf("$field"), "value" to listOf("$value"), "value2" to listOf("$value2")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/validate_field", diff --git a/kotlin/src/main/kotlin/org/openapitools/client/apis/SupportingApi.kt b/kotlin/src/main/kotlin/org/openapitools/client/apis/SupportingApi.kt index 297ca02..f17d5d3 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/apis/SupportingApi.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/apis/SupportingApi.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -12,7 +12,17 @@ package org.openapitools.client.apis -import org.openapitools.client.infrastructure.* +import org.openapitools.client.infrastructure.ApiClient +import org.openapitools.client.infrastructure.ClientException +import org.openapitools.client.infrastructure.ClientError +import org.openapitools.client.infrastructure.ServerException +import org.openapitools.client.infrastructure.ServerError +import org.openapitools.client.infrastructure.MultiValueMap +import org.openapitools.client.infrastructure.RequestConfig +import org.openapitools.client.infrastructure.RequestMethod +import org.openapitools.client.infrastructure.ResponseType +import org.openapitools.client.infrastructure.Success +import org.openapitools.client.infrastructure.toMultiValue class SupportingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : ApiClient(basePath) { @@ -25,7 +35,7 @@ class SupportingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") fun publicGetTimeGet() : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf() - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/get_time", @@ -56,7 +66,7 @@ class SupportingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") fun publicTestGet(expectedResult: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("expectedResult" to listOf("$expectedResult")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/public/test", diff --git a/kotlin/src/main/kotlin/org/openapitools/client/apis/TradingApi.kt b/kotlin/src/main/kotlin/org/openapitools/client/apis/TradingApi.kt index ce0a2d9..36d7da7 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/apis/TradingApi.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/apis/TradingApi.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -12,7 +12,17 @@ package org.openapitools.client.apis -import org.openapitools.client.infrastructure.* +import org.openapitools.client.infrastructure.ApiClient +import org.openapitools.client.infrastructure.ClientException +import org.openapitools.client.infrastructure.ClientError +import org.openapitools.client.infrastructure.ServerException +import org.openapitools.client.infrastructure.ServerError +import org.openapitools.client.infrastructure.MultiValueMap +import org.openapitools.client.infrastructure.RequestConfig +import org.openapitools.client.infrastructure.RequestMethod +import org.openapitools.client.infrastructure.ResponseType +import org.openapitools.client.infrastructure.Success +import org.openapitools.client.infrastructure.toMultiValue class TradingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : ApiClient(basePath) { @@ -37,7 +47,7 @@ class TradingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateBuyGet(instrumentName: kotlin.String, amount: java.math.BigDecimal, type: kotlin.String?, label: kotlin.String?, price: java.math.BigDecimal?, timeInForce: kotlin.String?, maxShow: java.math.BigDecimal?, postOnly: kotlin.Boolean?, reduceOnly: kotlin.Boolean?, stopPrice: java.math.BigDecimal?, trigger: kotlin.String?, advanced: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "amount" to listOf("$amount"), "type" to listOf("$type"), "label" to listOf("$label"), "price" to listOf("$price"), "timeInForce" to listOf("$timeInForce"), "maxShow" to listOf("$maxShow"), "postOnly" to listOf("$postOnly"), "reduceOnly" to listOf("$reduceOnly"), "stopPrice" to listOf("$stopPrice"), "trigger" to listOf("$trigger"), "advanced" to listOf("$advanced")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/buy", @@ -70,7 +80,7 @@ class TradingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateCancelAllByCurrencyGet(currency: kotlin.String, kind: kotlin.String?, type: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "kind" to listOf("$kind"), "type" to listOf("$type")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/cancel_all_by_currency", @@ -102,7 +112,7 @@ class TradingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateCancelAllByInstrumentGet(instrumentName: kotlin.String, type: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "type" to listOf("$type")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/cancel_all_by_instrument", @@ -132,7 +142,7 @@ class TradingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateCancelAllGet() : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf() - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/cancel_all", @@ -163,7 +173,7 @@ class TradingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateCancelGet(orderId: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("orderId" to listOf("$orderId")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/cancel", @@ -196,7 +206,7 @@ class TradingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateClosePositionGet(instrumentName: kotlin.String, type: kotlin.String, price: java.math.BigDecimal?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "type" to listOf("$type"), "price" to listOf("$price")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/close_position", @@ -232,7 +242,7 @@ class TradingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateEditGet(orderId: kotlin.String, amount: java.math.BigDecimal, price: java.math.BigDecimal, postOnly: kotlin.Boolean?, advanced: kotlin.String?, stopPrice: java.math.BigDecimal?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("orderId" to listOf("$orderId"), "amount" to listOf("$amount"), "price" to listOf("$price"), "postOnly" to listOf("$postOnly"), "advanced" to listOf("$advanced"), "stopPrice" to listOf("$stopPrice")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/edit", @@ -265,7 +275,7 @@ class TradingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetMarginsGet(instrumentName: kotlin.String, amount: java.math.BigDecimal, price: java.math.BigDecimal) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "amount" to listOf("$amount"), "price" to listOf("$price")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_margins", @@ -298,7 +308,7 @@ class TradingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetOpenOrdersByCurrencyGet(currency: kotlin.String, kind: kotlin.String?, type: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "kind" to listOf("$kind"), "type" to listOf("$type")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_open_orders_by_currency", @@ -330,7 +340,7 @@ class TradingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetOpenOrdersByInstrumentGet(instrumentName: kotlin.String, type: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "type" to listOf("$type")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_open_orders_by_instrument", @@ -366,7 +376,7 @@ class TradingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetOrderHistoryByCurrencyGet(currency: kotlin.String, kind: kotlin.String?, count: kotlin.Int?, offset: kotlin.Int?, includeOld: kotlin.Boolean?, includeUnfilled: kotlin.Boolean?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "kind" to listOf("$kind"), "count" to listOf("$count"), "offset" to listOf("$offset"), "includeOld" to listOf("$includeOld"), "includeUnfilled" to listOf("$includeUnfilled")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_order_history_by_currency", @@ -401,7 +411,7 @@ class TradingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetOrderHistoryByInstrumentGet(instrumentName: kotlin.String, count: kotlin.Int?, offset: kotlin.Int?, includeOld: kotlin.Boolean?, includeUnfilled: kotlin.Boolean?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "count" to listOf("$count"), "offset" to listOf("$offset"), "includeOld" to listOf("$includeOld"), "includeUnfilled" to listOf("$includeUnfilled")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_order_history_by_instrument", @@ -432,7 +442,7 @@ class TradingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetOrderMarginByIdsGet(ids: kotlin.Array) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("ids" to toMultiValue(ids.toList(), "multi")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_order_margin_by_ids", @@ -463,7 +473,7 @@ class TradingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetOrderStateGet(orderId: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("orderId" to listOf("$orderId")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_order_state", @@ -496,7 +506,7 @@ class TradingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetSettlementHistoryByCurrencyGet(currency: kotlin.String, type: kotlin.String?, count: kotlin.Int?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "type" to listOf("$type"), "count" to listOf("$count")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_settlement_history_by_currency", @@ -529,7 +539,7 @@ class TradingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetSettlementHistoryByInstrumentGet(instrumentName: kotlin.String, type: kotlin.String?, count: kotlin.Int?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "type" to listOf("$type"), "count" to listOf("$count")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_settlement_history_by_instrument", @@ -566,7 +576,7 @@ class TradingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetUserTradesByCurrencyAndTimeGet(currency: kotlin.String, startTimestamp: kotlin.Int, endTimestamp: kotlin.Int, kind: kotlin.String?, count: kotlin.Int?, includeOld: kotlin.Boolean?, sorting: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "kind" to listOf("$kind"), "startTimestamp" to listOf("$startTimestamp"), "endTimestamp" to listOf("$endTimestamp"), "count" to listOf("$count"), "includeOld" to listOf("$includeOld"), "sorting" to listOf("$sorting")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_user_trades_by_currency_and_time", @@ -603,7 +613,7 @@ class TradingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetUserTradesByCurrencyGet(currency: kotlin.String, kind: kotlin.String?, startId: kotlin.String?, endId: kotlin.String?, count: kotlin.Int?, includeOld: kotlin.Boolean?, sorting: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "kind" to listOf("$kind"), "startId" to listOf("$startId"), "endId" to listOf("$endId"), "count" to listOf("$count"), "includeOld" to listOf("$includeOld"), "sorting" to listOf("$sorting")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_user_trades_by_currency", @@ -639,7 +649,7 @@ class TradingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetUserTradesByInstrumentAndTimeGet(instrumentName: kotlin.String, startTimestamp: kotlin.Int, endTimestamp: kotlin.Int, count: kotlin.Int?, includeOld: kotlin.Boolean?, sorting: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "startTimestamp" to listOf("$startTimestamp"), "endTimestamp" to listOf("$endTimestamp"), "count" to listOf("$count"), "includeOld" to listOf("$includeOld"), "sorting" to listOf("$sorting")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_user_trades_by_instrument_and_time", @@ -675,7 +685,7 @@ class TradingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetUserTradesByInstrumentGet(instrumentName: kotlin.String, startSeq: kotlin.Int?, endSeq: kotlin.Int?, count: kotlin.Int?, includeOld: kotlin.Boolean?, sorting: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "startSeq" to listOf("$startSeq"), "endSeq" to listOf("$endSeq"), "count" to listOf("$count"), "includeOld" to listOf("$includeOld"), "sorting" to listOf("$sorting")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_user_trades_by_instrument", @@ -707,7 +717,7 @@ class TradingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateGetUserTradesByOrderGet(orderId: kotlin.String, sorting: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("orderId" to listOf("$orderId"), "sorting" to listOf("$sorting")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_user_trades_by_order", @@ -749,7 +759,7 @@ class TradingApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : A fun privateSellGet(instrumentName: kotlin.String, amount: java.math.BigDecimal, type: kotlin.String?, label: kotlin.String?, price: java.math.BigDecimal?, timeInForce: kotlin.String?, maxShow: java.math.BigDecimal?, postOnly: kotlin.Boolean?, reduceOnly: kotlin.Boolean?, stopPrice: java.math.BigDecimal?, trigger: kotlin.String?, advanced: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("instrumentName" to listOf("$instrumentName"), "amount" to listOf("$amount"), "type" to listOf("$type"), "label" to listOf("$label"), "price" to listOf("$price"), "timeInForce" to listOf("$timeInForce"), "maxShow" to listOf("$maxShow"), "postOnly" to listOf("$postOnly"), "reduceOnly" to listOf("$reduceOnly"), "stopPrice" to listOf("$stopPrice"), "trigger" to listOf("$trigger"), "advanced" to listOf("$advanced")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/sell", diff --git a/kotlin/src/main/kotlin/org/openapitools/client/apis/WalletApi.kt b/kotlin/src/main/kotlin/org/openapitools/client/apis/WalletApi.kt index 5887a35..566cd2c 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/apis/WalletApi.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/apis/WalletApi.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). @@ -12,7 +12,17 @@ package org.openapitools.client.apis -import org.openapitools.client.infrastructure.* +import org.openapitools.client.infrastructure.ApiClient +import org.openapitools.client.infrastructure.ClientException +import org.openapitools.client.infrastructure.ClientError +import org.openapitools.client.infrastructure.ServerException +import org.openapitools.client.infrastructure.ServerError +import org.openapitools.client.infrastructure.MultiValueMap +import org.openapitools.client.infrastructure.RequestConfig +import org.openapitools.client.infrastructure.RequestMethod +import org.openapitools.client.infrastructure.ResponseType +import org.openapitools.client.infrastructure.Success +import org.openapitools.client.infrastructure.toMultiValue class WalletApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : ApiClient(basePath) { @@ -30,7 +40,7 @@ class WalletApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun privateAddToAddressBookGet(currency: kotlin.String, type: kotlin.String, address: kotlin.String, name: kotlin.String, tfa: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "type" to listOf("$type"), "address" to listOf("$address"), "name" to listOf("$name"), "tfa" to listOf("$tfa")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/add_to_address_book", @@ -63,7 +73,7 @@ class WalletApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun privateCancelTransferByIdGet(currency: kotlin.String, id: kotlin.Int, tfa: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "id" to listOf("$id"), "tfa" to listOf("$tfa")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/cancel_transfer_by_id", @@ -95,7 +105,7 @@ class WalletApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun privateCancelWithdrawalGet(currency: kotlin.String, id: java.math.BigDecimal) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "id" to listOf("$id")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/cancel_withdrawal", @@ -126,7 +136,7 @@ class WalletApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun privateCreateDepositAddressGet(currency: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/create_deposit_address", @@ -158,7 +168,7 @@ class WalletApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun privateGetAddressBookGet(currency: kotlin.String, type: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "type" to listOf("$type")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_address_book", @@ -189,7 +199,7 @@ class WalletApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun privateGetCurrentDepositAddressGet(currency: kotlin.String) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_current_deposit_address", @@ -222,7 +232,7 @@ class WalletApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun privateGetDepositsGet(currency: kotlin.String, count: kotlin.Int?, offset: kotlin.Int?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "count" to listOf("$count"), "offset" to listOf("$offset")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_deposits", @@ -255,7 +265,7 @@ class WalletApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun privateGetTransfersGet(currency: kotlin.String, count: kotlin.Int?, offset: kotlin.Int?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "count" to listOf("$count"), "offset" to listOf("$offset")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_transfers", @@ -288,7 +298,7 @@ class WalletApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun privateGetWithdrawalsGet(currency: kotlin.String, count: kotlin.Int?, offset: kotlin.Int?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "count" to listOf("$count"), "offset" to listOf("$offset")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/get_withdrawals", @@ -322,7 +332,7 @@ class WalletApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun privateRemoveFromAddressBookGet(currency: kotlin.String, type: kotlin.String, address: kotlin.String, tfa: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "type" to listOf("$type"), "address" to listOf("$address"), "tfa" to listOf("$tfa")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/remove_from_address_book", @@ -355,7 +365,7 @@ class WalletApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun privateSubmitTransferToSubaccountGet(currency: kotlin.String, amount: java.math.BigDecimal, destination: kotlin.Int) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "amount" to listOf("$amount"), "destination" to listOf("$destination")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/submit_transfer_to_subaccount", @@ -389,7 +399,7 @@ class WalletApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun privateSubmitTransferToUserGet(currency: kotlin.String, amount: java.math.BigDecimal, destination: kotlin.String, tfa: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "amount" to listOf("$amount"), "destination" to listOf("$destination"), "tfa" to listOf("$tfa")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/submit_transfer_to_user", @@ -421,7 +431,7 @@ class WalletApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun privateToggleDepositAddressCreationGet(currency: kotlin.String, state: kotlin.Boolean) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "state" to listOf("$state")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/toggle_deposit_address_creation", @@ -456,7 +466,7 @@ class WalletApi(basePath: kotlin.String = "https://www.deribit.com/api/v2") : Ap fun privateWithdrawGet(currency: kotlin.String, address: kotlin.String, amount: java.math.BigDecimal, priority: kotlin.String?, tfa: kotlin.String?) : kotlin.Any { val localVariableBody: kotlin.Any? = null val localVariableQuery: MultiValueMap = mapOf("currency" to listOf("$currency"), "address" to listOf("$address"), "amount" to listOf("$amount"), "priority" to listOf("$priority"), "tfa" to listOf("$tfa")) - val localVariableHeaders: kotlin.collections.Map = mapOf() + val localVariableHeaders: MutableMap = mutableMapOf() val localVariableConfig = RequestConfig( RequestMethod.GET, "/private/withdraw", diff --git a/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 9e79028..c9107fc 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -1,11 +1,13 @@ package org.openapitools.client.infrastructure -import com.squareup.moshi.FromJson -import com.squareup.moshi.Moshi -import com.squareup.moshi.ToJson -import okhttp3.* +import okhttp3.OkHttpClient +import okhttp3.RequestBody +import okhttp3.MediaType +import okhttp3.FormBody +import okhttp3.HttpUrl +import okhttp3.ResponseBody +import okhttp3.Request import java.io.File -import java.util.* open class ApiClient(val baseUrl: String) { companion object { @@ -13,74 +15,75 @@ open class ApiClient(val baseUrl: String) { protected const val Accept = "Accept" protected const val JsonMediaType = "application/json" protected const val FormDataMediaType = "multipart/form-data" + protected const val FormUrlEncMediaType = "application/x-www-form-urlencoded" protected const val XmlMediaType = "application/xml" @JvmStatic - val client by lazy { + val client: OkHttpClient by lazy { builder.build() } @JvmStatic val builder: OkHttpClient.Builder = OkHttpClient.Builder() - - @JvmStatic - var defaultHeaders: Map by ApplicationDelegates.setOnce(mapOf(ContentType to JsonMediaType, Accept to JsonMediaType)) - - @JvmStatic - val jsonHeaders: Map = mapOf(ContentType to JsonMediaType, Accept to JsonMediaType) } protected inline fun requestBody(content: T, mediaType: String = JsonMediaType): RequestBody = - when { - content is File -> RequestBody.create( - MediaType.parse(mediaType), content - ) - mediaType == FormDataMediaType -> { - var builder = FormBody.Builder() - // content's type *must* be Map - @Suppress("UNCHECKED_CAST") - (content as Map).forEach { key, value -> - builder = builder.add(key, value) - } - builder.build() - } - mediaType == JsonMediaType -> RequestBody.create( - MediaType.parse(mediaType), Serializer.moshi.adapter(T::class.java).toJson(content) - ) - mediaType == XmlMediaType -> TODO("xml not currently supported.") - // TODO: this should be extended with other serializers - else -> TODO("requestBody currently only supports JSON body and File body.") - } + when { + content is File -> RequestBody.create( + MediaType.parse(mediaType), content + ) + mediaType == FormDataMediaType || mediaType == FormUrlEncMediaType -> { + FormBody.Builder().apply { + // content's type *must* be Map + @Suppress("UNCHECKED_CAST") + (content as Map).forEach { (key, value) -> + add(key, value) + } + }.build() + } + mediaType == JsonMediaType -> RequestBody.create( + MediaType.parse(mediaType), Serializer.moshi.adapter(T::class.java).toJson(content) + ) + mediaType == XmlMediaType -> TODO("xml not currently supported.") + // TODO: this should be extended with other serializers + else -> TODO("requestBody currently only supports JSON body and File body.") + } - protected inline fun responseBody(body: ResponseBody?, mediaType: String = JsonMediaType): T? { - if(body == null) return null + protected inline fun responseBody(body: ResponseBody?, mediaType: String? = JsonMediaType): T? { + if(body == null) { + return null + } + val bodyContent = body.string() + if (bodyContent.isEmpty()) { + return null + } return when(mediaType) { - JsonMediaType -> Moshi.Builder().add(object { - @ToJson - fun toJson(uuid: UUID) = uuid.toString() - @FromJson - fun fromJson(s: String) = UUID.fromString(s) - }) - .add(ByteArrayAdapter()) - .build().adapter(T::class.java).fromJson(body.source()) - else -> TODO() + JsonMediaType -> Serializer.moshi.adapter(T::class.java).fromJson(bodyContent) + else -> TODO("responseBody currently only supports JSON body.") } } protected inline fun request(requestConfig: RequestConfig, body : Any? = null): ApiInfrastructureResponse { val httpUrl = HttpUrl.parse(baseUrl) ?: throw IllegalStateException("baseUrl is invalid.") - var urlBuilder = httpUrl.newBuilder() - .addPathSegments(requestConfig.path.trimStart('/')) - - requestConfig.query.forEach { query -> - query.value.forEach { queryValue -> - urlBuilder = urlBuilder.addQueryParameter(query.key, queryValue) - } + val url = httpUrl.newBuilder() + .addPathSegments(requestConfig.path.trimStart('/')) + .apply { + requestConfig.query.forEach { query -> + query.value.forEach { queryValue -> + addQueryParameter(query.key, queryValue) + } + } + }.build() + + // take content-type/accept from spec or set to default (application/json) if not defined + if (requestConfig.headers[ContentType].isNullOrEmpty()) { + requestConfig.headers[ContentType] = JsonMediaType } - - val url = urlBuilder.build() - val headers = requestConfig.headers + defaultHeaders + if (requestConfig.headers[Accept].isNullOrEmpty()) { + requestConfig.headers[Accept] = JsonMediaType + } + val headers = requestConfig.headers if(headers[ContentType] ?: "" == "") { throw kotlin.IllegalStateException("Missing Content-Type header. This is required.") @@ -90,11 +93,10 @@ open class ApiClient(val baseUrl: String) { throw kotlin.IllegalStateException("Missing Accept header. This is required.") } - // TODO: support multiple contentType,accept options here. + // TODO: support multiple contentType options here. val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase() - val accept = (headers[Accept] as String).substringBefore(";").toLowerCase() - var request : Request.Builder = when (requestConfig.method) { + val request = when (requestConfig.method) { RequestMethod.DELETE -> Request.Builder().url(url).delete() RequestMethod.GET -> Request.Builder().url(url) RequestMethod.HEAD -> Request.Builder().url(url).head() @@ -102,12 +104,12 @@ open class ApiClient(val baseUrl: String) { RequestMethod.PUT -> Request.Builder().url(url).put(requestBody(body, contentType)) RequestMethod.POST -> Request.Builder().url(url).post(requestBody(body, contentType)) RequestMethod.OPTIONS -> Request.Builder().url(url).method("OPTIONS", null) - } - - headers.forEach { header -> request = request.addHeader(header.key, header.value) } + }.apply { + headers.forEach { header -> addHeader(header.key, header.value) } + }.build() - val realRequest = request.build() - val response = client.newCall(realRequest).execute() + val response = client.newCall(request).execute() + val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase() // TODO: handle specific mapping types. e.g. Map> when { @@ -138,4 +140,4 @@ open class ApiClient(val baseUrl: String) { ) } } -} \ No newline at end of file +} diff --git a/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt b/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt new file mode 100644 index 0000000..b2e1654 --- /dev/null +++ b/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt @@ -0,0 +1,19 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.time.LocalDate +import java.time.format.DateTimeFormatter + +class LocalDateAdapter { + @ToJson + fun toJson(value: LocalDate): String { + return DateTimeFormatter.ISO_LOCAL_DATE.format(value) + } + + @FromJson + fun fromJson(value: String): LocalDate { + return LocalDate.parse(value, DateTimeFormatter.ISO_LOCAL_DATE) + } + +} diff --git a/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt b/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt new file mode 100644 index 0000000..e082db9 --- /dev/null +++ b/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt @@ -0,0 +1,19 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.time.LocalDateTime +import java.time.format.DateTimeFormatter + +class LocalDateTimeAdapter { + @ToJson + fun toJson(value: LocalDateTime): String { + return DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(value) + } + + @FromJson + fun fromJson(value: String): LocalDateTime { + return LocalDateTime.parse(value, DateTimeFormatter.ISO_LOCAL_DATE_TIME) + } + +} diff --git a/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index 86e2dad..53e6892 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -11,6 +11,6 @@ package org.openapitools.client.infrastructure data class RequestConfig( val method: RequestMethod, val path: String, - val headers: Map = mapOf(), + val headers: MutableMap = mutableMapOf(), val query: Map> = mapOf() ) \ No newline at end of file diff --git a/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index cf3fe82..7c5a353 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -1,14 +1,18 @@ package org.openapitools.client.infrastructure -import com.squareup.moshi.KotlinJsonAdapterFactory import com.squareup.moshi.Moshi -import com.squareup.moshi.Rfc3339DateJsonAdapter -import java.util.* +import com.squareup.moshi.adapters.Rfc3339DateJsonAdapter +import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory +import java.util.Date object Serializer { @JvmStatic val moshi: Moshi = Moshi.Builder() - .add(KotlinJsonAdapterFactory()) .add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe()) + .add(LocalDateTimeAdapter()) + .add(LocalDateAdapter()) + .add(UUIDAdapter()) + .add(ByteArrayAdapter()) + .add(KotlinJsonAdapterFactory()) .build() } diff --git a/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt new file mode 100644 index 0000000..a4a44cc --- /dev/null +++ b/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -0,0 +1,13 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.util.UUID + +class UUIDAdapter { + @ToJson + fun toJson(uuid: UUID) = uuid.toString() + + @FromJson + fun fromJson(s: String) = UUID.fromString(s) +} diff --git a/kotlin/src/main/kotlin/org/openapitools/client/models/AddressBookItem.kt b/kotlin/src/main/kotlin/org/openapitools/client/models/AddressBookItem.kt index 6f05bc2..41404e9 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/models/AddressBookItem.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/models/AddressBookItem.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/kotlin/src/main/kotlin/org/openapitools/client/models/BookSummary.kt b/kotlin/src/main/kotlin/org/openapitools/client/models/BookSummary.kt index 1e42065..16e7d0a 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/models/BookSummary.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/models/BookSummary.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/kotlin/src/main/kotlin/org/openapitools/client/models/Currency.kt b/kotlin/src/main/kotlin/org/openapitools/client/models/Currency.kt index 6a39af5..c8c0c06 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/models/Currency.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/models/Currency.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/kotlin/src/main/kotlin/org/openapitools/client/models/CurrencyPortfolio.kt b/kotlin/src/main/kotlin/org/openapitools/client/models/CurrencyPortfolio.kt index 31d67b1..7f646a1 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/models/CurrencyPortfolio.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/models/CurrencyPortfolio.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/kotlin/src/main/kotlin/org/openapitools/client/models/CurrencyWithdrawalPriorities.kt b/kotlin/src/main/kotlin/org/openapitools/client/models/CurrencyWithdrawalPriorities.kt index 6389892..3c4a4f9 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/models/CurrencyWithdrawalPriorities.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/models/CurrencyWithdrawalPriorities.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/kotlin/src/main/kotlin/org/openapitools/client/models/Deposit.kt b/kotlin/src/main/kotlin/org/openapitools/client/models/Deposit.kt index e7acd13..d6c0289 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/models/Deposit.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/models/Deposit.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/kotlin/src/main/kotlin/org/openapitools/client/models/Instrument.kt b/kotlin/src/main/kotlin/org/openapitools/client/models/Instrument.kt index e2983ad..1b08401 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/models/Instrument.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/models/Instrument.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/kotlin/src/main/kotlin/org/openapitools/client/models/KeyNumberPair.kt b/kotlin/src/main/kotlin/org/openapitools/client/models/KeyNumberPair.kt index 018694e..2465d5e 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/models/KeyNumberPair.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/models/KeyNumberPair.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/kotlin/src/main/kotlin/org/openapitools/client/models/Order.kt b/kotlin/src/main/kotlin/org/openapitools/client/models/Order.kt index 2b2ebbe..36f9378 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/kotlin/src/main/kotlin/org/openapitools/client/models/OrderIdInitialMarginPair.kt b/kotlin/src/main/kotlin/org/openapitools/client/models/OrderIdInitialMarginPair.kt index 57d6500..ea6ec6b 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/models/OrderIdInitialMarginPair.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/models/OrderIdInitialMarginPair.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/kotlin/src/main/kotlin/org/openapitools/client/models/Portfolio.kt b/kotlin/src/main/kotlin/org/openapitools/client/models/Portfolio.kt index c3b14b2..cf371f4 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/models/Portfolio.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/models/Portfolio.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/kotlin/src/main/kotlin/org/openapitools/client/models/PortfolioEth.kt b/kotlin/src/main/kotlin/org/openapitools/client/models/PortfolioEth.kt index 105e392..5e61ad4 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/models/PortfolioEth.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/models/PortfolioEth.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/kotlin/src/main/kotlin/org/openapitools/client/models/Position.kt b/kotlin/src/main/kotlin/org/openapitools/client/models/Position.kt index 4458545..022cdbe 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/models/Position.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/models/Position.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/kotlin/src/main/kotlin/org/openapitools/client/models/PublicTrade.kt b/kotlin/src/main/kotlin/org/openapitools/client/models/PublicTrade.kt index 88fa540..04f150c 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/models/PublicTrade.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/models/PublicTrade.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/kotlin/src/main/kotlin/org/openapitools/client/models/Settlement.kt b/kotlin/src/main/kotlin/org/openapitools/client/models/Settlement.kt index 0df2bec..91fc142 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/models/Settlement.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/models/Settlement.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/kotlin/src/main/kotlin/org/openapitools/client/models/TradesVolumes.kt b/kotlin/src/main/kotlin/org/openapitools/client/models/TradesVolumes.kt index 712a126..db9c218 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/models/TradesVolumes.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/models/TradesVolumes.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/kotlin/src/main/kotlin/org/openapitools/client/models/TransferItem.kt b/kotlin/src/main/kotlin/org/openapitools/client/models/TransferItem.kt index 3c8f900..7dbe74b 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/models/TransferItem.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/models/TransferItem.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/kotlin/src/main/kotlin/org/openapitools/client/models/Types.kt b/kotlin/src/main/kotlin/org/openapitools/client/models/Types.kt index fa8e038..8ac6eff 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/models/Types.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/models/Types.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/kotlin/src/main/kotlin/org/openapitools/client/models/UserTrade.kt b/kotlin/src/main/kotlin/org/openapitools/client/models/UserTrade.kt index d1123f5..3c254aa 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/models/UserTrade.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/models/UserTrade.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/kotlin/src/main/kotlin/org/openapitools/client/models/Withdrawal.kt b/kotlin/src/main/kotlin/org/openapitools/client/models/Withdrawal.kt index cfa95ac..b2d3b8a 100644 --- a/kotlin/src/main/kotlin/org/openapitools/client/models/Withdrawal.kt +++ b/kotlin/src/main/kotlin/org/openapitools/client/models/Withdrawal.kt @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/.openapi-generator/VERSION b/objc/.openapi-generator/VERSION index afa6365..d96260b 100644 --- a/objc/.openapi-generator/VERSION +++ b/objc/.openapi-generator/VERSION @@ -1 +1 @@ -4.0.0-SNAPSHOT \ No newline at end of file +4.0.2-SNAPSHOT \ No newline at end of file diff --git a/objc/OpenAPIClient/Api/OAIAccountManagementApi.h b/objc/OpenAPIClient/Api/OAIAccountManagementApi.h index d6ea4c9..41b440e 100644 --- a/objc/OpenAPIClient/Api/OAIAccountManagementApi.h +++ b/objc/OpenAPIClient/Api/OAIAccountManagementApi.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Api/OAIAuthenticationApi.h b/objc/OpenAPIClient/Api/OAIAuthenticationApi.h index f997462..35d3997 100644 --- a/objc/OpenAPIClient/Api/OAIAuthenticationApi.h +++ b/objc/OpenAPIClient/Api/OAIAuthenticationApi.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Api/OAIInternalApi.h b/objc/OpenAPIClient/Api/OAIInternalApi.h index 28f5b0d..ccbc47b 100644 --- a/objc/OpenAPIClient/Api/OAIInternalApi.h +++ b/objc/OpenAPIClient/Api/OAIInternalApi.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Api/OAIMarketDataApi.h b/objc/OpenAPIClient/Api/OAIMarketDataApi.h index 46fbd18..a9c0cf6 100644 --- a/objc/OpenAPIClient/Api/OAIMarketDataApi.h +++ b/objc/OpenAPIClient/Api/OAIMarketDataApi.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Api/OAIPrivateApi.h b/objc/OpenAPIClient/Api/OAIPrivateApi.h index 7cb1084..03bccbf 100644 --- a/objc/OpenAPIClient/Api/OAIPrivateApi.h +++ b/objc/OpenAPIClient/Api/OAIPrivateApi.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Api/OAIPublicApi.h b/objc/OpenAPIClient/Api/OAIPublicApi.h index cd56379..776999a 100644 --- a/objc/OpenAPIClient/Api/OAIPublicApi.h +++ b/objc/OpenAPIClient/Api/OAIPublicApi.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Api/OAISupportingApi.h b/objc/OpenAPIClient/Api/OAISupportingApi.h index ca38069..a4a0be2 100644 --- a/objc/OpenAPIClient/Api/OAISupportingApi.h +++ b/objc/OpenAPIClient/Api/OAISupportingApi.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Api/OAITradingApi.h b/objc/OpenAPIClient/Api/OAITradingApi.h index beaeca5..01434f2 100644 --- a/objc/OpenAPIClient/Api/OAITradingApi.h +++ b/objc/OpenAPIClient/Api/OAITradingApi.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Api/OAIWalletApi.h b/objc/OpenAPIClient/Api/OAIWalletApi.h index d4457ca..04c6066 100644 --- a/objc/OpenAPIClient/Api/OAIWalletApi.h +++ b/objc/OpenAPIClient/Api/OAIWalletApi.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Core/JSONValueTransformer+ISO8601.h b/objc/OpenAPIClient/Core/JSONValueTransformer+ISO8601.h index 6d6f19f..146637f 100644 --- a/objc/OpenAPIClient/Core/JSONValueTransformer+ISO8601.h +++ b/objc/OpenAPIClient/Core/JSONValueTransformer+ISO8601.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Core/OAIApi.h b/objc/OpenAPIClient/Core/OAIApi.h index 0a20834..62fdd08 100644 --- a/objc/OpenAPIClient/Core/OAIApi.h +++ b/objc/OpenAPIClient/Core/OAIApi.h @@ -6,7 +6,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Core/OAIApiClient.h b/objc/OpenAPIClient/Core/OAIApiClient.h index c5c6e81..02fc121 100644 --- a/objc/OpenAPIClient/Core/OAIApiClient.h +++ b/objc/OpenAPIClient/Core/OAIApiClient.h @@ -7,7 +7,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Core/OAIConfiguration.h b/objc/OpenAPIClient/Core/OAIConfiguration.h index 95ad49c..946c171 100644 --- a/objc/OpenAPIClient/Core/OAIConfiguration.h +++ b/objc/OpenAPIClient/Core/OAIConfiguration.h @@ -6,7 +6,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Core/OAIDefaultConfiguration.h b/objc/OpenAPIClient/Core/OAIDefaultConfiguration.h index 40a0c40..2b4383d 100644 --- a/objc/OpenAPIClient/Core/OAIDefaultConfiguration.h +++ b/objc/OpenAPIClient/Core/OAIDefaultConfiguration.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Core/OAIJSONRequestSerializer.h b/objc/OpenAPIClient/Core/OAIJSONRequestSerializer.h index 5a78c6e..e181a6d 100644 --- a/objc/OpenAPIClient/Core/OAIJSONRequestSerializer.h +++ b/objc/OpenAPIClient/Core/OAIJSONRequestSerializer.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Core/OAILogger.h b/objc/OpenAPIClient/Core/OAILogger.h index 90cf475..8b9f4a7 100644 --- a/objc/OpenAPIClient/Core/OAILogger.h +++ b/objc/OpenAPIClient/Core/OAILogger.h @@ -4,7 +4,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Core/OAIObject.h b/objc/OpenAPIClient/Core/OAIObject.h index 2227564..9d14410 100644 --- a/objc/OpenAPIClient/Core/OAIObject.h +++ b/objc/OpenAPIClient/Core/OAIObject.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Core/OAIQueryParamCollection.h b/objc/OpenAPIClient/Core/OAIQueryParamCollection.h index 4219e50..2e96599 100644 --- a/objc/OpenAPIClient/Core/OAIQueryParamCollection.h +++ b/objc/OpenAPIClient/Core/OAIQueryParamCollection.h @@ -4,7 +4,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Core/OAIResponseDeserializer.h b/objc/OpenAPIClient/Core/OAIResponseDeserializer.h index a1444e9..6504187 100644 --- a/objc/OpenAPIClient/Core/OAIResponseDeserializer.h +++ b/objc/OpenAPIClient/Core/OAIResponseDeserializer.h @@ -4,7 +4,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Core/OAISanitizer.h b/objc/OpenAPIClient/Core/OAISanitizer.h index 0bcb8c6..351e4cf 100644 --- a/objc/OpenAPIClient/Core/OAISanitizer.h +++ b/objc/OpenAPIClient/Core/OAISanitizer.h @@ -4,7 +4,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Model/OAIAddressBookItem.h b/objc/OpenAPIClient/Model/OAIAddressBookItem.h index e10c051..2ad31fa 100644 --- a/objc/OpenAPIClient/Model/OAIAddressBookItem.h +++ b/objc/OpenAPIClient/Model/OAIAddressBookItem.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Model/OAIBookSummary.h b/objc/OpenAPIClient/Model/OAIBookSummary.h index ef916c5..61359cf 100644 --- a/objc/OpenAPIClient/Model/OAIBookSummary.h +++ b/objc/OpenAPIClient/Model/OAIBookSummary.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Model/OAICurrency.h b/objc/OpenAPIClient/Model/OAICurrency.h index 1d66519..0f8a9ff 100644 --- a/objc/OpenAPIClient/Model/OAICurrency.h +++ b/objc/OpenAPIClient/Model/OAICurrency.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Model/OAICurrencyPortfolio.h b/objc/OpenAPIClient/Model/OAICurrencyPortfolio.h index 9cd5cf7..9de8f57 100644 --- a/objc/OpenAPIClient/Model/OAICurrencyPortfolio.h +++ b/objc/OpenAPIClient/Model/OAICurrencyPortfolio.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Model/OAICurrencyWithdrawalPriorities.h b/objc/OpenAPIClient/Model/OAICurrencyWithdrawalPriorities.h index b2f75c6..ac53d9f 100644 --- a/objc/OpenAPIClient/Model/OAICurrencyWithdrawalPriorities.h +++ b/objc/OpenAPIClient/Model/OAICurrencyWithdrawalPriorities.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Model/OAIDeposit.h b/objc/OpenAPIClient/Model/OAIDeposit.h index f45f217..971f5de 100644 --- a/objc/OpenAPIClient/Model/OAIDeposit.h +++ b/objc/OpenAPIClient/Model/OAIDeposit.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Model/OAIInstrument.h b/objc/OpenAPIClient/Model/OAIInstrument.h index f3ac79b..a9ea7fe 100644 --- a/objc/OpenAPIClient/Model/OAIInstrument.h +++ b/objc/OpenAPIClient/Model/OAIInstrument.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Model/OAIKeyNumberPair.h b/objc/OpenAPIClient/Model/OAIKeyNumberPair.h index 0e0933f..93761d4 100644 --- a/objc/OpenAPIClient/Model/OAIKeyNumberPair.h +++ b/objc/OpenAPIClient/Model/OAIKeyNumberPair.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Model/OAIOrder.h b/objc/OpenAPIClient/Model/OAIOrder.h index 533c305..fc2ccb0 100644 --- a/objc/OpenAPIClient/Model/OAIOrder.h +++ b/objc/OpenAPIClient/Model/OAIOrder.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Model/OAIOrderIdInitialMarginPair.h b/objc/OpenAPIClient/Model/OAIOrderIdInitialMarginPair.h index 0c44289..b649505 100644 --- a/objc/OpenAPIClient/Model/OAIOrderIdInitialMarginPair.h +++ b/objc/OpenAPIClient/Model/OAIOrderIdInitialMarginPair.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Model/OAIPortfolio.h b/objc/OpenAPIClient/Model/OAIPortfolio.h index c8470c6..3493846 100644 --- a/objc/OpenAPIClient/Model/OAIPortfolio.h +++ b/objc/OpenAPIClient/Model/OAIPortfolio.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Model/OAIPortfolioEth.h b/objc/OpenAPIClient/Model/OAIPortfolioEth.h index 6279350..c724267 100644 --- a/objc/OpenAPIClient/Model/OAIPortfolioEth.h +++ b/objc/OpenAPIClient/Model/OAIPortfolioEth.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Model/OAIPosition.h b/objc/OpenAPIClient/Model/OAIPosition.h index f8cc64e..188a09d 100644 --- a/objc/OpenAPIClient/Model/OAIPosition.h +++ b/objc/OpenAPIClient/Model/OAIPosition.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Model/OAIPublicTrade.h b/objc/OpenAPIClient/Model/OAIPublicTrade.h index b95b69b..abceab6 100644 --- a/objc/OpenAPIClient/Model/OAIPublicTrade.h +++ b/objc/OpenAPIClient/Model/OAIPublicTrade.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Model/OAISettlement.h b/objc/OpenAPIClient/Model/OAISettlement.h index 78c7936..fd554c0 100644 --- a/objc/OpenAPIClient/Model/OAISettlement.h +++ b/objc/OpenAPIClient/Model/OAISettlement.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Model/OAITradesVolumes.h b/objc/OpenAPIClient/Model/OAITradesVolumes.h index 0ea3925..3ac48f1 100644 --- a/objc/OpenAPIClient/Model/OAITradesVolumes.h +++ b/objc/OpenAPIClient/Model/OAITradesVolumes.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Model/OAITransferItem.h b/objc/OpenAPIClient/Model/OAITransferItem.h index 9fdb0d8..56a117d 100644 --- a/objc/OpenAPIClient/Model/OAITransferItem.h +++ b/objc/OpenAPIClient/Model/OAITransferItem.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Model/OAITypes.h b/objc/OpenAPIClient/Model/OAITypes.h index d1f4a23..6860739 100644 --- a/objc/OpenAPIClient/Model/OAITypes.h +++ b/objc/OpenAPIClient/Model/OAITypes.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Model/OAIUserTrade.h b/objc/OpenAPIClient/Model/OAIUserTrade.h index fe592c5..80ca218 100644 --- a/objc/OpenAPIClient/Model/OAIUserTrade.h +++ b/objc/OpenAPIClient/Model/OAIUserTrade.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/objc/OpenAPIClient/Model/OAIWithdrawal.h b/objc/OpenAPIClient/Model/OAIWithdrawal.h index d2599a6..2d5442b 100644 --- a/objc/OpenAPIClient/Model/OAIWithdrawal.h +++ b/objc/OpenAPIClient/Model/OAIWithdrawal.h @@ -5,7 +5,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * -* OpenAPI spec version: 2.0.0 +* The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/php/.openapi-generator/VERSION b/php/.openapi-generator/VERSION index afa6365..d96260b 100644 --- a/php/.openapi-generator/VERSION +++ b/php/.openapi-generator/VERSION @@ -1 +1 @@ -4.0.0-SNAPSHOT \ No newline at end of file +4.0.2-SNAPSHOT \ No newline at end of file diff --git a/php/lib/Api/AccountManagementApi.php b/php/lib/Api/AccountManagementApi.php index 7f689fc..6018f22 100644 --- a/php/lib/Api/AccountManagementApi.php +++ b/php/lib/Api/AccountManagementApi.php @@ -14,10 +14,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Api/AuthenticationApi.php b/php/lib/Api/AuthenticationApi.php index bcb349b..2d61760 100644 --- a/php/lib/Api/AuthenticationApi.php +++ b/php/lib/Api/AuthenticationApi.php @@ -14,10 +14,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Api/InternalApi.php b/php/lib/Api/InternalApi.php index 12c6718..108d559 100644 --- a/php/lib/Api/InternalApi.php +++ b/php/lib/Api/InternalApi.php @@ -14,10 +14,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Api/MarketDataApi.php b/php/lib/Api/MarketDataApi.php index 6fa3bda..01d8f20 100644 --- a/php/lib/Api/MarketDataApi.php +++ b/php/lib/Api/MarketDataApi.php @@ -14,10 +14,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Api/PrivateApi.php b/php/lib/Api/PrivateApi.php index 9125278..d9c54ee 100644 --- a/php/lib/Api/PrivateApi.php +++ b/php/lib/Api/PrivateApi.php @@ -14,10 +14,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Api/PublicApi.php b/php/lib/Api/PublicApi.php index f676bc4..15ac6b8 100644 --- a/php/lib/Api/PublicApi.php +++ b/php/lib/Api/PublicApi.php @@ -14,10 +14,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Api/SupportingApi.php b/php/lib/Api/SupportingApi.php index fe0a5ac..ecad12e 100644 --- a/php/lib/Api/SupportingApi.php +++ b/php/lib/Api/SupportingApi.php @@ -14,10 +14,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Api/TradingApi.php b/php/lib/Api/TradingApi.php index b8a3b29..3e32bad 100644 --- a/php/lib/Api/TradingApi.php +++ b/php/lib/Api/TradingApi.php @@ -14,10 +14,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Api/WalletApi.php b/php/lib/Api/WalletApi.php index 3b377c8..dc7706b 100644 --- a/php/lib/Api/WalletApi.php +++ b/php/lib/Api/WalletApi.php @@ -14,10 +14,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/ApiException.php b/php/lib/ApiException.php index ab02632..92b17f3 100644 --- a/php/lib/ApiException.php +++ b/php/lib/ApiException.php @@ -14,10 +14,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Configuration.php b/php/lib/Configuration.php index d78f8cd..8492dd1 100644 --- a/php/lib/Configuration.php +++ b/php/lib/Configuration.php @@ -14,10 +14,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** @@ -396,7 +396,7 @@ public static function toDebugReport() $report = 'PHP SDK (OpenAPI\Client) Debug Report:' . PHP_EOL; $report .= ' OS: ' . php_uname() . PHP_EOL; $report .= ' PHP Version: ' . PHP_VERSION . PHP_EOL; - $report .= ' OpenAPI Spec Version: 2.0.0' . PHP_EOL; + $report .= ' The version of the OpenAPI document: 2.0.0' . PHP_EOL; $report .= ' Temp Folder Path: ' . self::getDefaultConfiguration()->getTempFolderPath() . PHP_EOL; return $report; diff --git a/php/lib/HeaderSelector.php b/php/lib/HeaderSelector.php index 843009a..1e20212 100644 --- a/php/lib/HeaderSelector.php +++ b/php/lib/HeaderSelector.php @@ -14,10 +14,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Model/AddressBookItem.php b/php/lib/Model/AddressBookItem.php index a5600bb..7a1fd44 100644 --- a/php/lib/Model/AddressBookItem.php +++ b/php/lib/Model/AddressBookItem.php @@ -15,10 +15,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Model/BookSummary.php b/php/lib/Model/BookSummary.php index 6813f7c..b62a065 100644 --- a/php/lib/Model/BookSummary.php +++ b/php/lib/Model/BookSummary.php @@ -15,10 +15,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Model/Currency.php b/php/lib/Model/Currency.php index fc53154..d5ccd4a 100644 --- a/php/lib/Model/Currency.php +++ b/php/lib/Model/Currency.php @@ -15,10 +15,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Model/CurrencyPortfolio.php b/php/lib/Model/CurrencyPortfolio.php index f164310..952dc50 100644 --- a/php/lib/Model/CurrencyPortfolio.php +++ b/php/lib/Model/CurrencyPortfolio.php @@ -15,10 +15,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Model/CurrencyWithdrawalPriorities.php b/php/lib/Model/CurrencyWithdrawalPriorities.php index f44fafb..c61dd25 100644 --- a/php/lib/Model/CurrencyWithdrawalPriorities.php +++ b/php/lib/Model/CurrencyWithdrawalPriorities.php @@ -15,10 +15,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Model/Deposit.php b/php/lib/Model/Deposit.php index e047ad2..8f68cbb 100644 --- a/php/lib/Model/Deposit.php +++ b/php/lib/Model/Deposit.php @@ -15,10 +15,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Model/Instrument.php b/php/lib/Model/Instrument.php index 4344804..05ba89b 100644 --- a/php/lib/Model/Instrument.php +++ b/php/lib/Model/Instrument.php @@ -15,10 +15,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Model/KeyNumberPair.php b/php/lib/Model/KeyNumberPair.php index e6e88c3..d4306c8 100644 --- a/php/lib/Model/KeyNumberPair.php +++ b/php/lib/Model/KeyNumberPair.php @@ -15,10 +15,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Model/ModelInterface.php b/php/lib/Model/ModelInterface.php index 992575c..082cff9 100644 --- a/php/lib/Model/ModelInterface.php +++ b/php/lib/Model/ModelInterface.php @@ -15,10 +15,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Model/Order.php b/php/lib/Model/Order.php index d8bf81f..cdaf60f 100644 --- a/php/lib/Model/Order.php +++ b/php/lib/Model/Order.php @@ -15,10 +15,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Model/OrderIdInitialMarginPair.php b/php/lib/Model/OrderIdInitialMarginPair.php index f6cf016..9607506 100644 --- a/php/lib/Model/OrderIdInitialMarginPair.php +++ b/php/lib/Model/OrderIdInitialMarginPair.php @@ -15,10 +15,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Model/Portfolio.php b/php/lib/Model/Portfolio.php index d746861..bb824ec 100644 --- a/php/lib/Model/Portfolio.php +++ b/php/lib/Model/Portfolio.php @@ -15,10 +15,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Model/PortfolioEth.php b/php/lib/Model/PortfolioEth.php index 407a9ea..019a99b 100644 --- a/php/lib/Model/PortfolioEth.php +++ b/php/lib/Model/PortfolioEth.php @@ -15,10 +15,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Model/Position.php b/php/lib/Model/Position.php index 6f24b7b..1430078 100644 --- a/php/lib/Model/Position.php +++ b/php/lib/Model/Position.php @@ -15,10 +15,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Model/PublicTrade.php b/php/lib/Model/PublicTrade.php index c66696e..174f9b4 100644 --- a/php/lib/Model/PublicTrade.php +++ b/php/lib/Model/PublicTrade.php @@ -15,10 +15,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Model/Settlement.php b/php/lib/Model/Settlement.php index c6d9db1..faa4ba4 100644 --- a/php/lib/Model/Settlement.php +++ b/php/lib/Model/Settlement.php @@ -15,10 +15,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Model/TradesVolumes.php b/php/lib/Model/TradesVolumes.php index dbd06e4..aeb990a 100644 --- a/php/lib/Model/TradesVolumes.php +++ b/php/lib/Model/TradesVolumes.php @@ -15,10 +15,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Model/TransferItem.php b/php/lib/Model/TransferItem.php index 0533fd0..57819e5 100644 --- a/php/lib/Model/TransferItem.php +++ b/php/lib/Model/TransferItem.php @@ -15,10 +15,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Model/Types.php b/php/lib/Model/Types.php index 884ef7a..c9a427a 100644 --- a/php/lib/Model/Types.php +++ b/php/lib/Model/Types.php @@ -15,10 +15,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Model/UserTrade.php b/php/lib/Model/UserTrade.php index db46179..7cba647 100644 --- a/php/lib/Model/UserTrade.php +++ b/php/lib/Model/UserTrade.php @@ -15,10 +15,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/Model/Withdrawal.php b/php/lib/Model/Withdrawal.php index b982bdf..08270c7 100644 --- a/php/lib/Model/Withdrawal.php +++ b/php/lib/Model/Withdrawal.php @@ -15,10 +15,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/php/lib/ObjectSerializer.php b/php/lib/ObjectSerializer.php index 2ce8129..0ce1ba5 100644 --- a/php/lib/ObjectSerializer.php +++ b/php/lib/ObjectSerializer.php @@ -15,10 +15,10 @@ * * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 4.0.0-SNAPSHOT + * OpenAPI Generator version: 4.0.2-SNAPSHOT */ /** diff --git a/python/.openapi-generator/VERSION b/python/.openapi-generator/VERSION index afa6365..d96260b 100644 --- a/python/.openapi-generator/VERSION +++ b/python/.openapi-generator/VERSION @@ -1 +1 @@ -4.0.0-SNAPSHOT \ No newline at end of file +4.0.2-SNAPSHOT \ No newline at end of file diff --git a/python/docs/AccountManagementApi.md b/python/docs/AccountManagementApi.md index e189887..61a33a6 100644 --- a/python/docs/AccountManagementApi.md +++ b/python/docs/AccountManagementApi.md @@ -73,6 +73,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_create_subaccount_get** @@ -120,6 +125,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_disable_tfa_for_subaccount_get** @@ -171,6 +181,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_account_summary_get** @@ -224,6 +239,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_email_language_get** @@ -271,6 +291,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_new_announcements_get** @@ -318,6 +343,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_position_get** @@ -369,6 +399,12 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | When successful returns position | - | +**400** | When some error occurs | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_positions_get** @@ -422,6 +458,12 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | When successful returns array of positions | - | +**400** | When some error occurs | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_subaccounts_get** @@ -473,6 +515,12 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | +**401** | not authorised | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_set_announcement_as_read_get** @@ -524,6 +572,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_set_email_for_subaccount_get** @@ -577,6 +630,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_set_email_language_get** @@ -628,6 +686,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_set_password_for_subaccount_get** @@ -681,6 +744,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_toggle_notifications_from_subaccount_get** @@ -734,6 +802,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_toggle_subaccount_login_get** @@ -787,6 +860,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_announcements_get** @@ -834,5 +912,10 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/python/docs/AuthenticationApi.md b/python/docs/AuthenticationApi.md index 4c0808e..2e35a8c 100644 --- a/python/docs/AuthenticationApi.md +++ b/python/docs/AuthenticationApi.md @@ -78,5 +78,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | +**429** | over limit | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/python/docs/InternalApi.md b/python/docs/InternalApi.md index 23efb7f..d1f25fb 100644 --- a/python/docs/InternalApi.md +++ b/python/docs/InternalApi.md @@ -73,6 +73,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_disable_tfa_with_recovery_code_get** @@ -126,6 +131,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_address_book_get** @@ -179,6 +189,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_remove_from_address_book_get** @@ -236,6 +251,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_submit_transfer_to_subaccount_get** @@ -291,6 +311,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_submit_transfer_to_user_get** @@ -348,6 +373,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_toggle_deposit_address_creation_get** @@ -401,6 +431,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_footer_get** @@ -448,6 +483,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_option_mark_prices_get** @@ -499,6 +539,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_validate_field_get** @@ -554,5 +599,10 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/python/docs/MarketDataApi.md b/python/docs/MarketDataApi.md index f9ec98c..0365d92 100644 --- a/python/docs/MarketDataApi.md +++ b/python/docs/MarketDataApi.md @@ -75,6 +75,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_book_summary_by_instrument_get** @@ -126,6 +131,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_contract_size_get** @@ -177,6 +187,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_currencies_get** @@ -224,6 +239,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_funding_chart_data_get** @@ -277,6 +297,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_historical_volatility_get** @@ -328,6 +353,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_index_get** @@ -379,6 +409,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_instruments_get** @@ -434,6 +469,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_last_settlements_by_currency_get** @@ -493,6 +533,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_last_settlements_by_instrument_get** @@ -552,6 +597,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_last_trades_by_currency_and_time_get** @@ -615,6 +665,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_last_trades_by_currency_get** @@ -678,6 +733,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_last_trades_by_instrument_and_time_get** @@ -739,6 +799,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_last_trades_by_instrument_get** @@ -800,6 +865,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_order_book_get** @@ -853,6 +923,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_trade_volumes_get** @@ -900,6 +975,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_tradingview_chart_data_get** @@ -955,6 +1035,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_ticker_get** @@ -1006,5 +1091,10 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/python/docs/PrivateApi.md b/python/docs/PrivateApi.md index 1735737..704f1dc 100644 --- a/python/docs/PrivateApi.md +++ b/python/docs/PrivateApi.md @@ -115,6 +115,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_buy_get** @@ -188,6 +193,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_cancel_all_by_currency_get** @@ -243,6 +253,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_cancel_all_by_instrument_get** @@ -296,6 +311,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_cancel_all_get** @@ -343,6 +363,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_cancel_get** @@ -394,6 +419,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_cancel_transfer_by_id_get** @@ -449,6 +479,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_cancel_withdrawal_get** @@ -502,6 +537,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_change_subaccount_name_get** @@ -555,6 +595,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_close_position_get** @@ -610,6 +655,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_create_deposit_address_get** @@ -661,6 +711,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_create_subaccount_get** @@ -708,6 +763,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_disable_tfa_for_subaccount_get** @@ -759,6 +819,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_disable_tfa_with_recovery_code_get** @@ -812,6 +877,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_edit_get** @@ -873,6 +943,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_account_summary_get** @@ -926,6 +1001,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_address_book_get** @@ -979,6 +1059,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_current_deposit_address_get** @@ -1030,6 +1115,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_deposits_get** @@ -1085,6 +1175,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_email_language_get** @@ -1132,6 +1227,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_margins_get** @@ -1187,6 +1287,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_new_announcements_get** @@ -1234,6 +1339,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_open_orders_by_currency_get** @@ -1289,6 +1399,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_open_orders_by_instrument_get** @@ -1342,6 +1457,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_order_history_by_currency_get** @@ -1403,6 +1523,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_order_history_by_instrument_get** @@ -1462,6 +1587,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_order_margin_by_ids_get** @@ -1513,6 +1643,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_order_state_get** @@ -1564,6 +1699,12 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | +**400** | result when used via rest/HTTP | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_position_get** @@ -1615,6 +1756,12 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | When successful returns position | - | +**400** | When some error occurs | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_positions_get** @@ -1668,6 +1815,12 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | When successful returns array of positions | - | +**400** | When some error occurs | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_settlement_history_by_currency_get** @@ -1723,6 +1876,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_settlement_history_by_instrument_get** @@ -1778,6 +1936,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_subaccounts_get** @@ -1829,6 +1992,12 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | +**401** | not authorised | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_transfers_get** @@ -1884,6 +2053,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_user_trades_by_currency_and_time_get** @@ -1947,6 +2121,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_user_trades_by_currency_get** @@ -2010,6 +2189,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_user_trades_by_instrument_and_time_get** @@ -2071,6 +2255,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_user_trades_by_instrument_get** @@ -2132,6 +2321,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_user_trades_by_order_get** @@ -2185,6 +2379,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_withdrawals_get** @@ -2240,6 +2439,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_remove_from_address_book_get** @@ -2297,6 +2501,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_sell_get** @@ -2370,6 +2579,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_set_announcement_as_read_get** @@ -2421,6 +2635,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_set_email_for_subaccount_get** @@ -2474,6 +2693,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_set_email_language_get** @@ -2525,6 +2749,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_set_password_for_subaccount_get** @@ -2578,6 +2807,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_submit_transfer_to_subaccount_get** @@ -2633,6 +2867,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_submit_transfer_to_user_get** @@ -2690,6 +2929,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_toggle_deposit_address_creation_get** @@ -2743,6 +2987,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_toggle_notifications_from_subaccount_get** @@ -2796,6 +3045,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_toggle_subaccount_login_get** @@ -2849,6 +3103,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_withdraw_get** @@ -2908,5 +3167,10 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/python/docs/PublicApi.md b/python/docs/PublicApi.md index a862b25..67055b5 100644 --- a/python/docs/PublicApi.md +++ b/python/docs/PublicApi.md @@ -100,6 +100,12 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | +**429** | over limit | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_announcements_get** @@ -147,6 +153,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_book_summary_by_currency_get** @@ -200,6 +211,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_book_summary_by_instrument_get** @@ -251,6 +267,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_contract_size_get** @@ -302,6 +323,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_currencies_get** @@ -349,6 +375,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_funding_chart_data_get** @@ -402,6 +433,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_historical_volatility_get** @@ -453,6 +489,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_index_get** @@ -504,6 +545,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_instruments_get** @@ -559,6 +605,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_last_settlements_by_currency_get** @@ -618,6 +669,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_last_settlements_by_instrument_get** @@ -677,6 +733,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_last_trades_by_currency_and_time_get** @@ -740,6 +801,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_last_trades_by_currency_get** @@ -803,6 +869,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_last_trades_by_instrument_and_time_get** @@ -864,6 +935,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_last_trades_by_instrument_get** @@ -925,6 +1001,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_order_book_get** @@ -978,6 +1059,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_time_get** @@ -1025,6 +1111,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_trade_volumes_get** @@ -1072,6 +1163,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_get_tradingview_chart_data_get** @@ -1127,6 +1223,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_test_get** @@ -1178,6 +1279,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_ticker_get** @@ -1229,6 +1335,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_validate_field_get** @@ -1284,5 +1395,10 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/python/docs/SupportingApi.md b/python/docs/SupportingApi.md index bec1b56..cd8822f 100644 --- a/python/docs/SupportingApi.md +++ b/python/docs/SupportingApi.md @@ -53,6 +53,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **public_test_get** @@ -104,5 +109,10 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/python/docs/TradingApi.md b/python/docs/TradingApi.md index af3d50e..c9b9fed 100644 --- a/python/docs/TradingApi.md +++ b/python/docs/TradingApi.md @@ -99,6 +99,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_cancel_all_by_currency_get** @@ -154,6 +159,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_cancel_all_by_instrument_get** @@ -207,6 +217,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_cancel_all_get** @@ -254,6 +269,11 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_cancel_get** @@ -305,6 +325,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_close_position_get** @@ -360,6 +385,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_edit_get** @@ -421,6 +451,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_margins_get** @@ -476,6 +511,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_open_orders_by_currency_get** @@ -531,6 +571,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_open_orders_by_instrument_get** @@ -584,6 +629,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_order_history_by_currency_get** @@ -645,6 +695,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_order_history_by_instrument_get** @@ -704,6 +759,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_order_margin_by_ids_get** @@ -755,6 +815,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_order_state_get** @@ -806,6 +871,12 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | +**400** | result when used via rest/HTTP | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_settlement_history_by_currency_get** @@ -861,6 +932,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_settlement_history_by_instrument_get** @@ -916,6 +992,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_user_trades_by_currency_and_time_get** @@ -979,6 +1060,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_user_trades_by_currency_get** @@ -1042,6 +1128,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_user_trades_by_instrument_and_time_get** @@ -1103,6 +1194,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_user_trades_by_instrument_get** @@ -1164,6 +1260,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_user_trades_by_order_get** @@ -1217,6 +1318,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_sell_get** @@ -1290,5 +1396,10 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/python/docs/WalletApi.md b/python/docs/WalletApi.md index 28e807b..b42d3b2 100644 --- a/python/docs/WalletApi.md +++ b/python/docs/WalletApi.md @@ -77,6 +77,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_cancel_transfer_by_id_get** @@ -132,6 +137,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_cancel_withdrawal_get** @@ -185,6 +195,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_create_deposit_address_get** @@ -236,6 +251,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_address_book_get** @@ -289,6 +309,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_current_deposit_address_get** @@ -340,6 +365,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_deposits_get** @@ -395,6 +425,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_transfers_get** @@ -450,6 +485,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_get_withdrawals_get** @@ -505,6 +545,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_remove_from_address_book_get** @@ -562,6 +607,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_submit_transfer_to_subaccount_get** @@ -617,6 +667,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | ok response | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_submit_transfer_to_user_get** @@ -674,6 +729,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_toggle_deposit_address_creation_get** @@ -727,6 +787,11 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **private_withdraw_get** @@ -786,5 +851,10 @@ Name | Type | Description | Notes - **Content-Type**: Not defined - **Accept**: application/json +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | | - | + [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/python/openapi_client/__init__.py b/python/openapi_client/__init__.py index 51dfa9d..7b4d339 100644 --- a/python/openapi_client/__init__.py +++ b/python/openapi_client/__init__.py @@ -7,7 +7,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/openapi_client/api/account_management_api.py b/python/openapi_client/api/account_management_api.py index 9a66bac..46ed12a 100644 --- a/python/openapi_client/api/account_management_api.py +++ b/python/openapi_client/api/account_management_api.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ @@ -44,19 +44,22 @@ def private_change_subaccount_name_get(self, sid, name, **kwargs): # noqa: E501 >>> thread = api.private_change_subaccount_name_get(sid, name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param int sid: The user id for the subaccount (required) :param str name: The new user name (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_change_subaccount_name_get_with_http_info(sid, name, **kwargs) # noqa: E501 - else: - (data) = self.private_change_subaccount_name_get_with_http_info(sid, name, **kwargs) # noqa: E501 - return data + return self.private_change_subaccount_name_get_with_http_info(sid, name, **kwargs) # noqa: E501 def private_change_subaccount_name_get_with_http_info(self, sid, name, **kwargs): # noqa: E501 """Change the user name for a subaccount # noqa: E501 @@ -66,10 +69,19 @@ def private_change_subaccount_name_get_with_http_info(self, sid, name, **kwargs) >>> thread = api.private_change_subaccount_name_get_with_http_info(sid, name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param int sid: The user id for the subaccount (required) :param str name: The new user name (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -146,17 +158,20 @@ def private_create_subaccount_get(self, **kwargs): # noqa: E501 >>> thread = api.private_create_subaccount_get(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_create_subaccount_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.private_create_subaccount_get_with_http_info(**kwargs) # noqa: E501 - return data + return self.private_create_subaccount_get_with_http_info(**kwargs) # noqa: E501 def private_create_subaccount_get_with_http_info(self, **kwargs): # noqa: E501 """Create a new subaccount # noqa: E501 @@ -166,8 +181,17 @@ def private_create_subaccount_get_with_http_info(self, **kwargs): # noqa: E501 >>> thread = api.private_create_subaccount_get_with_http_info(async_req=True) >>> result = thread.get() - :param async_req bool - :return: object + :param async_req bool: execute request asynchronously + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -232,18 +256,21 @@ def private_disable_tfa_for_subaccount_get(self, sid, **kwargs): # noqa: E501 >>> thread = api.private_disable_tfa_for_subaccount_get(sid, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param int sid: The user id for the subaccount (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_disable_tfa_for_subaccount_get_with_http_info(sid, **kwargs) # noqa: E501 - else: - (data) = self.private_disable_tfa_for_subaccount_get_with_http_info(sid, **kwargs) # noqa: E501 - return data + return self.private_disable_tfa_for_subaccount_get_with_http_info(sid, **kwargs) # noqa: E501 def private_disable_tfa_for_subaccount_get_with_http_info(self, sid, **kwargs): # noqa: E501 """Disable two factor authentication for a subaccount. # noqa: E501 @@ -253,9 +280,18 @@ def private_disable_tfa_for_subaccount_get_with_http_info(self, sid, **kwargs): >>> thread = api.private_disable_tfa_for_subaccount_get_with_http_info(sid, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param int sid: The user id for the subaccount (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -326,19 +362,22 @@ def private_get_account_summary_get(self, currency, **kwargs): # noqa: E501 >>> thread = api.private_get_account_summary_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param bool extended: Include additional fields + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_account_summary_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.private_get_account_summary_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.private_get_account_summary_get_with_http_info(currency, **kwargs) # noqa: E501 def private_get_account_summary_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieves user account summary. # noqa: E501 @@ -348,10 +387,19 @@ def private_get_account_summary_get_with_http_info(self, currency, **kwargs): # >>> thread = api.private_get_account_summary_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param bool extended: Include additional fields - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -424,17 +472,20 @@ def private_get_email_language_get(self, **kwargs): # noqa: E501 >>> thread = api.private_get_email_language_get(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_email_language_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.private_get_email_language_get_with_http_info(**kwargs) # noqa: E501 - return data + return self.private_get_email_language_get_with_http_info(**kwargs) # noqa: E501 def private_get_email_language_get_with_http_info(self, **kwargs): # noqa: E501 """Retrieves the language to be used for emails. # noqa: E501 @@ -444,8 +495,17 @@ def private_get_email_language_get_with_http_info(self, **kwargs): # noqa: E501 >>> thread = api.private_get_email_language_get_with_http_info(async_req=True) >>> result = thread.get() - :param async_req bool - :return: object + :param async_req bool: execute request asynchronously + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -510,17 +570,20 @@ def private_get_new_announcements_get(self, **kwargs): # noqa: E501 >>> thread = api.private_get_new_announcements_get(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_new_announcements_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.private_get_new_announcements_get_with_http_info(**kwargs) # noqa: E501 - return data + return self.private_get_new_announcements_get_with_http_info(**kwargs) # noqa: E501 def private_get_new_announcements_get_with_http_info(self, **kwargs): # noqa: E501 """Retrieves announcements that have not been marked read by the user. # noqa: E501 @@ -530,8 +593,17 @@ def private_get_new_announcements_get_with_http_info(self, **kwargs): # noqa: E >>> thread = api.private_get_new_announcements_get_with_http_info(async_req=True) >>> result = thread.get() - :param async_req bool - :return: object + :param async_req bool: execute request asynchronously + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -596,18 +668,21 @@ def private_get_position_get(self, instrument_name, **kwargs): # noqa: E501 >>> thread = api.private_get_position_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_position_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.private_get_position_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.private_get_position_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def private_get_position_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Retrieve user position. # noqa: E501 @@ -617,9 +692,18 @@ def private_get_position_get_with_http_info(self, instrument_name, **kwargs): # >>> thread = api.private_get_position_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -690,19 +774,22 @@ def private_get_positions_get(self, currency, **kwargs): # noqa: E501 >>> thread = api.private_get_positions_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: (required) :param str kind: Kind filter on positions + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_positions_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.private_get_positions_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.private_get_positions_get_with_http_info(currency, **kwargs) # noqa: E501 def private_get_positions_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieve user positions. # noqa: E501 @@ -712,10 +799,19 @@ def private_get_positions_get_with_http_info(self, currency, **kwargs): # noqa: >>> thread = api.private_get_positions_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: (required) :param str kind: Kind filter on positions - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -788,18 +884,21 @@ def private_get_subaccounts_get(self, **kwargs): # noqa: E501 >>> thread = api.private_get_subaccounts_get(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param bool with_portfolio: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_subaccounts_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.private_get_subaccounts_get_with_http_info(**kwargs) # noqa: E501 - return data + return self.private_get_subaccounts_get_with_http_info(**kwargs) # noqa: E501 def private_get_subaccounts_get_with_http_info(self, **kwargs): # noqa: E501 """Get information about subaccounts # noqa: E501 @@ -809,9 +908,18 @@ def private_get_subaccounts_get_with_http_info(self, **kwargs): # noqa: E501 >>> thread = api.private_get_subaccounts_get_with_http_info(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param bool with_portfolio: - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -878,18 +986,21 @@ def private_set_announcement_as_read_get(self, announcement_id, **kwargs): # no >>> thread = api.private_set_announcement_as_read_get(announcement_id, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param float announcement_id: the ID of the announcement (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_set_announcement_as_read_get_with_http_info(announcement_id, **kwargs) # noqa: E501 - else: - (data) = self.private_set_announcement_as_read_get_with_http_info(announcement_id, **kwargs) # noqa: E501 - return data + return self.private_set_announcement_as_read_get_with_http_info(announcement_id, **kwargs) # noqa: E501 def private_set_announcement_as_read_get_with_http_info(self, announcement_id, **kwargs): # noqa: E501 """Marks an announcement as read, so it will not be shown in `get_new_announcements`. # noqa: E501 @@ -899,9 +1010,18 @@ def private_set_announcement_as_read_get_with_http_info(self, announcement_id, * >>> thread = api.private_set_announcement_as_read_get_with_http_info(announcement_id, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param float announcement_id: the ID of the announcement (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -972,19 +1092,22 @@ def private_set_email_for_subaccount_get(self, sid, email, **kwargs): # noqa: E >>> thread = api.private_set_email_for_subaccount_get(sid, email, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param int sid: The user id for the subaccount (required) :param str email: The email address for the subaccount (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_set_email_for_subaccount_get_with_http_info(sid, email, **kwargs) # noqa: E501 - else: - (data) = self.private_set_email_for_subaccount_get_with_http_info(sid, email, **kwargs) # noqa: E501 - return data + return self.private_set_email_for_subaccount_get_with_http_info(sid, email, **kwargs) # noqa: E501 def private_set_email_for_subaccount_get_with_http_info(self, sid, email, **kwargs): # noqa: E501 """Assign an email address to a subaccount. User will receive an email with confirmation link. # noqa: E501 @@ -994,10 +1117,19 @@ def private_set_email_for_subaccount_get_with_http_info(self, sid, email, **kwar >>> thread = api.private_set_email_for_subaccount_get_with_http_info(sid, email, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param int sid: The user id for the subaccount (required) :param str email: The email address for the subaccount (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1074,18 +1206,21 @@ def private_set_email_language_get(self, language, **kwargs): # noqa: E501 >>> thread = api.private_set_email_language_get(language, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str language: The abbreviated language name. Valid values include `\"en\"`, `\"ko\"`, `\"zh\"` (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_set_email_language_get_with_http_info(language, **kwargs) # noqa: E501 - else: - (data) = self.private_set_email_language_get_with_http_info(language, **kwargs) # noqa: E501 - return data + return self.private_set_email_language_get_with_http_info(language, **kwargs) # noqa: E501 def private_set_email_language_get_with_http_info(self, language, **kwargs): # noqa: E501 """Changes the language to be used for emails. # noqa: E501 @@ -1095,9 +1230,18 @@ def private_set_email_language_get_with_http_info(self, language, **kwargs): # >>> thread = api.private_set_email_language_get_with_http_info(language, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str language: The abbreviated language name. Valid values include `\"en\"`, `\"ko\"`, `\"zh\"` (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1168,19 +1312,22 @@ def private_set_password_for_subaccount_get(self, sid, password, **kwargs): # n >>> thread = api.private_set_password_for_subaccount_get(sid, password, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param int sid: The user id for the subaccount (required) :param str password: The password for the subaccount (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_set_password_for_subaccount_get_with_http_info(sid, password, **kwargs) # noqa: E501 - else: - (data) = self.private_set_password_for_subaccount_get_with_http_info(sid, password, **kwargs) # noqa: E501 - return data + return self.private_set_password_for_subaccount_get_with_http_info(sid, password, **kwargs) # noqa: E501 def private_set_password_for_subaccount_get_with_http_info(self, sid, password, **kwargs): # noqa: E501 """Set the password for the subaccount # noqa: E501 @@ -1190,10 +1337,19 @@ def private_set_password_for_subaccount_get_with_http_info(self, sid, password, >>> thread = api.private_set_password_for_subaccount_get_with_http_info(sid, password, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param int sid: The user id for the subaccount (required) :param str password: The password for the subaccount (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1270,19 +1426,22 @@ def private_toggle_notifications_from_subaccount_get(self, sid, state, **kwargs) >>> thread = api.private_toggle_notifications_from_subaccount_get(sid, state, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param int sid: The user id for the subaccount (required) :param bool state: enable (`true`) or disable (`false`) notifications (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_toggle_notifications_from_subaccount_get_with_http_info(sid, state, **kwargs) # noqa: E501 - else: - (data) = self.private_toggle_notifications_from_subaccount_get_with_http_info(sid, state, **kwargs) # noqa: E501 - return data + return self.private_toggle_notifications_from_subaccount_get_with_http_info(sid, state, **kwargs) # noqa: E501 def private_toggle_notifications_from_subaccount_get_with_http_info(self, sid, state, **kwargs): # noqa: E501 """Enable or disable sending of notifications for the subaccount. # noqa: E501 @@ -1292,10 +1451,19 @@ def private_toggle_notifications_from_subaccount_get_with_http_info(self, sid, s >>> thread = api.private_toggle_notifications_from_subaccount_get_with_http_info(sid, state, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param int sid: The user id for the subaccount (required) :param bool state: enable (`true`) or disable (`false`) notifications (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1372,19 +1540,22 @@ def private_toggle_subaccount_login_get(self, sid, state, **kwargs): # noqa: E5 >>> thread = api.private_toggle_subaccount_login_get(sid, state, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param int sid: The user id for the subaccount (required) :param str state: enable or disable login. (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_toggle_subaccount_login_get_with_http_info(sid, state, **kwargs) # noqa: E501 - else: - (data) = self.private_toggle_subaccount_login_get_with_http_info(sid, state, **kwargs) # noqa: E501 - return data + return self.private_toggle_subaccount_login_get_with_http_info(sid, state, **kwargs) # noqa: E501 def private_toggle_subaccount_login_get_with_http_info(self, sid, state, **kwargs): # noqa: E501 """Enable or disable login for a subaccount. If login is disabled and a session for the subaccount exists, this session will be terminated. # noqa: E501 @@ -1394,10 +1565,19 @@ def private_toggle_subaccount_login_get_with_http_info(self, sid, state, **kwarg >>> thread = api.private_toggle_subaccount_login_get_with_http_info(sid, state, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param int sid: The user id for the subaccount (required) :param str state: enable or disable login. (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1474,17 +1654,20 @@ def public_get_announcements_get(self, **kwargs): # noqa: E501 >>> thread = api.public_get_announcements_get(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_announcements_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.public_get_announcements_get_with_http_info(**kwargs) # noqa: E501 - return data + return self.public_get_announcements_get_with_http_info(**kwargs) # noqa: E501 def public_get_announcements_get_with_http_info(self, **kwargs): # noqa: E501 """Retrieves announcements from the last 30 days. # noqa: E501 @@ -1494,8 +1677,17 @@ def public_get_announcements_get_with_http_info(self, **kwargs): # noqa: E501 >>> thread = api.public_get_announcements_get_with_http_info(async_req=True) >>> result = thread.get() - :param async_req bool - :return: object + :param async_req bool: execute request asynchronously + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ diff --git a/python/openapi_client/api/authentication_api.py b/python/openapi_client/api/authentication_api.py index 79afae2..6e7bc7d 100644 --- a/python/openapi_client/api/authentication_api.py +++ b/python/openapi_client/api/authentication_api.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ @@ -45,7 +45,7 @@ def public_auth_get(self, grant_type, username, password, client_id, client_secr >>> thread = api.public_auth_get(grant_type, username, password, client_id, client_secret, refresh_token, timestamp, signature, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str grant_type: Method of authentication (required) :param str username: Required for grant type `password` (required) :param str password: Required for grant type `password` (required) @@ -57,16 +57,19 @@ def public_auth_get(self, grant_type, username, password, client_id, client_secr :param str nonce: Optional for grant type `client_signature`; delivers user generated initialization vector for the server token :param str state: Will be passed back in the response :param str scope: Describes type of the access for assigned token, possible values: `connection`, `session`, `session:name`, `trade:[read, read_write, none]`, `wallet:[read, read_write, none]`, `account:[read, read_write, none]`, `expires:NUMBER` (token will expire after `NUMBER` of seconds).

**NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read``` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_auth_get_with_http_info(grant_type, username, password, client_id, client_secret, refresh_token, timestamp, signature, **kwargs) # noqa: E501 - else: - (data) = self.public_auth_get_with_http_info(grant_type, username, password, client_id, client_secret, refresh_token, timestamp, signature, **kwargs) # noqa: E501 - return data + return self.public_auth_get_with_http_info(grant_type, username, password, client_id, client_secret, refresh_token, timestamp, signature, **kwargs) # noqa: E501 def public_auth_get_with_http_info(self, grant_type, username, password, client_id, client_secret, refresh_token, timestamp, signature, **kwargs): # noqa: E501 """Authenticate # noqa: E501 @@ -77,7 +80,7 @@ def public_auth_get_with_http_info(self, grant_type, username, password, client_ >>> thread = api.public_auth_get_with_http_info(grant_type, username, password, client_id, client_secret, refresh_token, timestamp, signature, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str grant_type: Method of authentication (required) :param str username: Required for grant type `password` (required) :param str password: Required for grant type `password` (required) @@ -89,7 +92,16 @@ def public_auth_get_with_http_info(self, grant_type, username, password, client_ :param str nonce: Optional for grant type `client_signature`; delivers user generated initialization vector for the server token :param str state: Will be passed back in the response :param str scope: Describes type of the access for assigned token, possible values: `connection`, `session`, `session:name`, `trade:[read, read_write, none]`, `wallet:[read, read_write, none]`, `account:[read, read_write, none]`, `expires:NUMBER` (token will expire after `NUMBER` of seconds).

**NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read``` - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ diff --git a/python/openapi_client/api/internal_api.py b/python/openapi_client/api/internal_api.py index 6fec962..4f0c5c6 100644 --- a/python/openapi_client/api/internal_api.py +++ b/python/openapi_client/api/internal_api.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ @@ -44,22 +44,25 @@ def private_add_to_address_book_get(self, currency, type, address, name, **kwarg >>> thread = api.private_add_to_address_book_get(currency, type, address, name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Address book type (required) :param str address: Address in currency format, it must be in address book (required) :param str name: Name of address book entry (required) :param str tfa: TFA code, required when TFA is enabled for current account + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_add_to_address_book_get_with_http_info(currency, type, address, name, **kwargs) # noqa: E501 - else: - (data) = self.private_add_to_address_book_get_with_http_info(currency, type, address, name, **kwargs) # noqa: E501 - return data + return self.private_add_to_address_book_get_with_http_info(currency, type, address, name, **kwargs) # noqa: E501 def private_add_to_address_book_get_with_http_info(self, currency, type, address, name, **kwargs): # noqa: E501 """Adds new entry to address book of given type # noqa: E501 @@ -69,13 +72,22 @@ def private_add_to_address_book_get_with_http_info(self, currency, type, address >>> thread = api.private_add_to_address_book_get_with_http_info(currency, type, address, name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Address book type (required) :param str address: Address in currency format, it must be in address book (required) :param str name: Name of address book entry (required) :param str tfa: TFA code, required when TFA is enabled for current account - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -166,19 +178,22 @@ def private_disable_tfa_with_recovery_code_get(self, password, code, **kwargs): >>> thread = api.private_disable_tfa_with_recovery_code_get(password, code, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str password: The password for the subaccount (required) :param str code: One time recovery code (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_disable_tfa_with_recovery_code_get_with_http_info(password, code, **kwargs) # noqa: E501 - else: - (data) = self.private_disable_tfa_with_recovery_code_get_with_http_info(password, code, **kwargs) # noqa: E501 - return data + return self.private_disable_tfa_with_recovery_code_get_with_http_info(password, code, **kwargs) # noqa: E501 def private_disable_tfa_with_recovery_code_get_with_http_info(self, password, code, **kwargs): # noqa: E501 """Disables TFA with one time recovery code # noqa: E501 @@ -188,10 +203,19 @@ def private_disable_tfa_with_recovery_code_get_with_http_info(self, password, co >>> thread = api.private_disable_tfa_with_recovery_code_get_with_http_info(password, code, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str password: The password for the subaccount (required) :param str code: One time recovery code (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -268,19 +292,22 @@ def private_get_address_book_get(self, currency, type, **kwargs): # noqa: E501 >>> thread = api.private_get_address_book_get(currency, type, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Address book type (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_address_book_get_with_http_info(currency, type, **kwargs) # noqa: E501 - else: - (data) = self.private_get_address_book_get_with_http_info(currency, type, **kwargs) # noqa: E501 - return data + return self.private_get_address_book_get_with_http_info(currency, type, **kwargs) # noqa: E501 def private_get_address_book_get_with_http_info(self, currency, type, **kwargs): # noqa: E501 """Retrieves address book of given type # noqa: E501 @@ -290,10 +317,19 @@ def private_get_address_book_get_with_http_info(self, currency, type, **kwargs): >>> thread = api.private_get_address_book_get_with_http_info(currency, type, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Address book type (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -370,21 +406,24 @@ def private_remove_from_address_book_get(self, currency, type, address, **kwargs >>> thread = api.private_remove_from_address_book_get(currency, type, address, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Address book type (required) :param str address: Address in currency format, it must be in address book (required) :param str tfa: TFA code, required when TFA is enabled for current account + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_remove_from_address_book_get_with_http_info(currency, type, address, **kwargs) # noqa: E501 - else: - (data) = self.private_remove_from_address_book_get_with_http_info(currency, type, address, **kwargs) # noqa: E501 - return data + return self.private_remove_from_address_book_get_with_http_info(currency, type, address, **kwargs) # noqa: E501 def private_remove_from_address_book_get_with_http_info(self, currency, type, address, **kwargs): # noqa: E501 """Adds new entry to address book of given type # noqa: E501 @@ -394,12 +433,21 @@ def private_remove_from_address_book_get_with_http_info(self, currency, type, ad >>> thread = api.private_remove_from_address_book_get_with_http_info(currency, type, address, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Address book type (required) :param str address: Address in currency format, it must be in address book (required) :param str tfa: TFA code, required when TFA is enabled for current account - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -484,20 +532,23 @@ def private_submit_transfer_to_subaccount_get(self, currency, amount, destinatio >>> thread = api.private_submit_transfer_to_subaccount_get(currency, amount, destination, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param float amount: Amount of funds to be transferred (required) :param int destination: Id of destination subaccount (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_submit_transfer_to_subaccount_get_with_http_info(currency, amount, destination, **kwargs) # noqa: E501 - else: - (data) = self.private_submit_transfer_to_subaccount_get_with_http_info(currency, amount, destination, **kwargs) # noqa: E501 - return data + return self.private_submit_transfer_to_subaccount_get_with_http_info(currency, amount, destination, **kwargs) # noqa: E501 def private_submit_transfer_to_subaccount_get_with_http_info(self, currency, amount, destination, **kwargs): # noqa: E501 """Transfer funds to a subaccount. # noqa: E501 @@ -507,11 +558,20 @@ def private_submit_transfer_to_subaccount_get_with_http_info(self, currency, amo >>> thread = api.private_submit_transfer_to_subaccount_get_with_http_info(currency, amount, destination, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param float amount: Amount of funds to be transferred (required) :param int destination: Id of destination subaccount (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -594,21 +654,24 @@ def private_submit_transfer_to_user_get(self, currency, amount, destination, **k >>> thread = api.private_submit_transfer_to_user_get(currency, amount, destination, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param float amount: Amount of funds to be transferred (required) :param str destination: Destination address from address book (required) :param str tfa: TFA code, required when TFA is enabled for current account + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_submit_transfer_to_user_get_with_http_info(currency, amount, destination, **kwargs) # noqa: E501 - else: - (data) = self.private_submit_transfer_to_user_get_with_http_info(currency, amount, destination, **kwargs) # noqa: E501 - return data + return self.private_submit_transfer_to_user_get_with_http_info(currency, amount, destination, **kwargs) # noqa: E501 def private_submit_transfer_to_user_get_with_http_info(self, currency, amount, destination, **kwargs): # noqa: E501 """Transfer funds to a another user. # noqa: E501 @@ -618,12 +681,21 @@ def private_submit_transfer_to_user_get_with_http_info(self, currency, amount, d >>> thread = api.private_submit_transfer_to_user_get_with_http_info(currency, amount, destination, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param float amount: Amount of funds to be transferred (required) :param str destination: Destination address from address book (required) :param str tfa: TFA code, required when TFA is enabled for current account - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -708,19 +780,22 @@ def private_toggle_deposit_address_creation_get(self, currency, state, **kwargs) >>> thread = api.private_toggle_deposit_address_creation_get(currency, state, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param bool state: (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_toggle_deposit_address_creation_get_with_http_info(currency, state, **kwargs) # noqa: E501 - else: - (data) = self.private_toggle_deposit_address_creation_get_with_http_info(currency, state, **kwargs) # noqa: E501 - return data + return self.private_toggle_deposit_address_creation_get_with_http_info(currency, state, **kwargs) # noqa: E501 def private_toggle_deposit_address_creation_get_with_http_info(self, currency, state, **kwargs): # noqa: E501 """Enable or disable deposit address creation # noqa: E501 @@ -730,10 +805,19 @@ def private_toggle_deposit_address_creation_get_with_http_info(self, currency, s >>> thread = api.private_toggle_deposit_address_creation_get_with_http_info(currency, state, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param bool state: (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -810,17 +894,20 @@ def public_get_footer_get(self, **kwargs): # noqa: E501 >>> thread = api.public_get_footer_get(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_footer_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.public_get_footer_get_with_http_info(**kwargs) # noqa: E501 - return data + return self.public_get_footer_get_with_http_info(**kwargs) # noqa: E501 def public_get_footer_get_with_http_info(self, **kwargs): # noqa: E501 """Get information to be displayed in the footer of the website. # noqa: E501 @@ -830,8 +917,17 @@ def public_get_footer_get_with_http_info(self, **kwargs): # noqa: E501 >>> thread = api.public_get_footer_get_with_http_info(async_req=True) >>> result = thread.get() - :param async_req bool - :return: object + :param async_req bool: execute request asynchronously + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -896,18 +992,21 @@ def public_get_option_mark_prices_get(self, currency, **kwargs): # noqa: E501 >>> thread = api.public_get_option_mark_prices_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_option_mark_prices_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.public_get_option_mark_prices_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.public_get_option_mark_prices_get_with_http_info(currency, **kwargs) # noqa: E501 def public_get_option_mark_prices_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrives market prices and its implied volatility of options instruments # noqa: E501 @@ -917,9 +1016,18 @@ def public_get_option_mark_prices_get_with_http_info(self, currency, **kwargs): >>> thread = api.public_get_option_mark_prices_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -990,20 +1098,23 @@ def public_validate_field_get(self, field, value, **kwargs): # noqa: E501 >>> thread = api.public_validate_field_get(field, value, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str field: Name of the field to be validated, examples: postal_code, date_of_birth (required) :param str value: Value to be checked (required) :param str value2: Additional value to be compared with + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_validate_field_get_with_http_info(field, value, **kwargs) # noqa: E501 - else: - (data) = self.public_validate_field_get_with_http_info(field, value, **kwargs) # noqa: E501 - return data + return self.public_validate_field_get_with_http_info(field, value, **kwargs) # noqa: E501 def public_validate_field_get_with_http_info(self, field, value, **kwargs): # noqa: E501 """Method used to introduce the client software connected to Deribit platform over websocket. Provided data may have an impact on the maintained connection and will be collected for internal statistical purposes. In response, Deribit will also introduce itself. # noqa: E501 @@ -1013,11 +1124,20 @@ def public_validate_field_get_with_http_info(self, field, value, **kwargs): # n >>> thread = api.public_validate_field_get_with_http_info(field, value, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str field: Name of the field to be validated, examples: postal_code, date_of_birth (required) :param str value: Value to be checked (required) :param str value2: Additional value to be compared with - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ diff --git a/python/openapi_client/api/market_data_api.py b/python/openapi_client/api/market_data_api.py index 82810de..7ae9574 100644 --- a/python/openapi_client/api/market_data_api.py +++ b/python/openapi_client/api/market_data_api.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ @@ -44,19 +44,22 @@ def public_get_book_summary_by_currency_get(self, currency, **kwargs): # noqa: >>> thread = api.public_get_book_summary_by_currency_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_book_summary_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.public_get_book_summary_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.public_get_book_summary_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 def public_get_book_summary_by_currency_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieves the summary information such as open interest, 24h volume, etc. for all instruments for the currency (optionally filtered by kind). # noqa: E501 @@ -66,10 +69,19 @@ def public_get_book_summary_by_currency_get_with_http_info(self, currency, **kwa >>> thread = api.public_get_book_summary_by_currency_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -142,18 +154,21 @@ def public_get_book_summary_by_instrument_get(self, instrument_name, **kwargs): >>> thread = api.public_get_book_summary_by_instrument_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_book_summary_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.public_get_book_summary_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.public_get_book_summary_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def public_get_book_summary_by_instrument_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Retrieves the summary information such as open interest, 24h volume, etc. for a specific instrument. # noqa: E501 @@ -163,9 +178,18 @@ def public_get_book_summary_by_instrument_get_with_http_info(self, instrument_na >>> thread = api.public_get_book_summary_by_instrument_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -236,18 +260,21 @@ def public_get_contract_size_get(self, instrument_name, **kwargs): # noqa: E501 >>> thread = api.public_get_contract_size_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_contract_size_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.public_get_contract_size_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.public_get_contract_size_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def public_get_contract_size_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Retrieves contract size of provided instrument. # noqa: E501 @@ -257,9 +284,18 @@ def public_get_contract_size_get_with_http_info(self, instrument_name, **kwargs) >>> thread = api.public_get_contract_size_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -330,17 +366,20 @@ def public_get_currencies_get(self, **kwargs): # noqa: E501 >>> thread = api.public_get_currencies_get(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_currencies_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.public_get_currencies_get_with_http_info(**kwargs) # noqa: E501 - return data + return self.public_get_currencies_get_with_http_info(**kwargs) # noqa: E501 def public_get_currencies_get_with_http_info(self, **kwargs): # noqa: E501 """Retrieves all cryptocurrencies supported by the API. # noqa: E501 @@ -350,8 +389,17 @@ def public_get_currencies_get_with_http_info(self, **kwargs): # noqa: E501 >>> thread = api.public_get_currencies_get_with_http_info(async_req=True) >>> result = thread.get() - :param async_req bool - :return: object + :param async_req bool: execute request asynchronously + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -416,19 +464,22 @@ def public_get_funding_chart_data_get(self, instrument_name, **kwargs): # noqa: >>> thread = api.public_get_funding_chart_data_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param str length: Specifies time period. `8h` - 8 hours, `24h` - 24 hours + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_funding_chart_data_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.public_get_funding_chart_data_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.public_get_funding_chart_data_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def public_get_funding_chart_data_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Retrieve the latest user trades that have occurred for PERPETUAL instruments in a specific currency symbol and within given time range. # noqa: E501 @@ -438,10 +489,19 @@ def public_get_funding_chart_data_get_with_http_info(self, instrument_name, **kw >>> thread = api.public_get_funding_chart_data_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param str length: Specifies time period. `8h` - 8 hours, `24h` - 24 hours - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -514,18 +574,21 @@ def public_get_historical_volatility_get(self, currency, **kwargs): # noqa: E50 >>> thread = api.public_get_historical_volatility_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_historical_volatility_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.public_get_historical_volatility_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.public_get_historical_volatility_get_with_http_info(currency, **kwargs) # noqa: E501 def public_get_historical_volatility_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Provides information about historical volatility for given cryptocurrency. # noqa: E501 @@ -535,9 +598,18 @@ def public_get_historical_volatility_get_with_http_info(self, currency, **kwargs >>> thread = api.public_get_historical_volatility_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -608,18 +680,21 @@ def public_get_index_get(self, currency, **kwargs): # noqa: E501 >>> thread = api.public_get_index_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_index_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.public_get_index_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.public_get_index_get_with_http_info(currency, **kwargs) # noqa: E501 def public_get_index_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieves the current index price for the instruments, for the selected currency. # noqa: E501 @@ -629,9 +704,18 @@ def public_get_index_get_with_http_info(self, currency, **kwargs): # noqa: E501 >>> thread = api.public_get_index_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -702,20 +786,23 @@ def public_get_instruments_get(self, currency, **kwargs): # noqa: E501 >>> thread = api.public_get_instruments_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered :param bool expired: Set to true to show expired instruments instead of active ones. + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_instruments_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.public_get_instruments_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.public_get_instruments_get_with_http_info(currency, **kwargs) # noqa: E501 def public_get_instruments_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieves available trading instruments. This method can be used to see which instruments are available for trading, or which instruments have existed historically. # noqa: E501 @@ -725,11 +812,20 @@ def public_get_instruments_get_with_http_info(self, currency, **kwargs): # noqa >>> thread = api.public_get_instruments_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered :param bool expired: Set to true to show expired instruments instead of active ones. - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -804,22 +900,25 @@ def public_get_last_settlements_by_currency_get(self, currency, **kwargs): # no >>> thread = api.public_get_last_settlements_by_currency_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Settlement type :param int count: Number of requested items, default - `20` :param str continuation: Continuation token for pagination :param int search_start_timestamp: The latest timestamp to return result for + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_last_settlements_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.public_get_last_settlements_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.public_get_last_settlements_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 def public_get_last_settlements_by_currency_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieves historical settlement, delivery and bankruptcy events coming from all instruments within given currency. # noqa: E501 @@ -829,13 +928,22 @@ def public_get_last_settlements_by_currency_get_with_http_info(self, currency, * >>> thread = api.public_get_last_settlements_by_currency_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Settlement type :param int count: Number of requested items, default - `20` :param str continuation: Continuation token for pagination :param int search_start_timestamp: The latest timestamp to return result for - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -914,22 +1022,25 @@ def public_get_last_settlements_by_instrument_get(self, instrument_name, **kwarg >>> thread = api.public_get_last_settlements_by_instrument_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param str type: Settlement type :param int count: Number of requested items, default - `20` :param str continuation: Continuation token for pagination :param int search_start_timestamp: The latest timestamp to return result for + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_last_settlements_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.public_get_last_settlements_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.public_get_last_settlements_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def public_get_last_settlements_by_instrument_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Retrieves historical public settlement, delivery and bankruptcy events filtered by instrument name. # noqa: E501 @@ -939,13 +1050,22 @@ def public_get_last_settlements_by_instrument_get_with_http_info(self, instrumen >>> thread = api.public_get_last_settlements_by_instrument_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param str type: Settlement type :param int count: Number of requested items, default - `20` :param str continuation: Continuation token for pagination :param int search_start_timestamp: The latest timestamp to return result for - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1024,7 +1144,7 @@ def public_get_last_trades_by_currency_and_time_get(self, currency, start_timest >>> thread = api.public_get_last_trades_by_currency_and_time_get(currency, start_timestamp, end_timestamp, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param int start_timestamp: The earliest timestamp to return result for (required) :param int end_timestamp: The most recent timestamp to return result for (required) @@ -1032,16 +1152,19 @@ def public_get_last_trades_by_currency_and_time_get(self, currency, start_timest :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_last_trades_by_currency_and_time_get_with_http_info(currency, start_timestamp, end_timestamp, **kwargs) # noqa: E501 - else: - (data) = self.public_get_last_trades_by_currency_and_time_get_with_http_info(currency, start_timestamp, end_timestamp, **kwargs) # noqa: E501 - return data + return self.public_get_last_trades_by_currency_and_time_get_with_http_info(currency, start_timestamp, end_timestamp, **kwargs) # noqa: E501 def public_get_last_trades_by_currency_and_time_get_with_http_info(self, currency, start_timestamp, end_timestamp, **kwargs): # noqa: E501 """Retrieve the latest trades that have occurred for instruments in a specific currency symbol and within given time range. # noqa: E501 @@ -1051,7 +1174,7 @@ def public_get_last_trades_by_currency_and_time_get_with_http_info(self, currenc >>> thread = api.public_get_last_trades_by_currency_and_time_get_with_http_info(currency, start_timestamp, end_timestamp, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param int start_timestamp: The earliest timestamp to return result for (required) :param int end_timestamp: The most recent timestamp to return result for (required) @@ -1059,7 +1182,16 @@ def public_get_last_trades_by_currency_and_time_get_with_http_info(self, currenc :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1150,7 +1282,7 @@ def public_get_last_trades_by_currency_get(self, currency, **kwargs): # noqa: E >>> thread = api.public_get_last_trades_by_currency_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered :param str start_id: The ID number of the first trade to be returned @@ -1158,16 +1290,19 @@ def public_get_last_trades_by_currency_get(self, currency, **kwargs): # noqa: E :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_last_trades_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.public_get_last_trades_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.public_get_last_trades_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 def public_get_last_trades_by_currency_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieve the latest trades that have occurred for instruments in a specific currency symbol. # noqa: E501 @@ -1177,7 +1312,7 @@ def public_get_last_trades_by_currency_get_with_http_info(self, currency, **kwar >>> thread = api.public_get_last_trades_by_currency_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered :param str start_id: The ID number of the first trade to be returned @@ -1185,7 +1320,16 @@ def public_get_last_trades_by_currency_get_with_http_info(self, currency, **kwar :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1268,23 +1412,26 @@ def public_get_last_trades_by_instrument_and_time_get(self, instrument_name, sta >>> thread = api.public_get_last_trades_by_instrument_and_time_get(instrument_name, start_timestamp, end_timestamp, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param int start_timestamp: The earliest timestamp to return result for (required) :param int end_timestamp: The most recent timestamp to return result for (required) :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_last_trades_by_instrument_and_time_get_with_http_info(instrument_name, start_timestamp, end_timestamp, **kwargs) # noqa: E501 - else: - (data) = self.public_get_last_trades_by_instrument_and_time_get_with_http_info(instrument_name, start_timestamp, end_timestamp, **kwargs) # noqa: E501 - return data + return self.public_get_last_trades_by_instrument_and_time_get_with_http_info(instrument_name, start_timestamp, end_timestamp, **kwargs) # noqa: E501 def public_get_last_trades_by_instrument_and_time_get_with_http_info(self, instrument_name, start_timestamp, end_timestamp, **kwargs): # noqa: E501 """Retrieve the latest trades that have occurred for a specific instrument and within given time range. # noqa: E501 @@ -1294,14 +1441,23 @@ def public_get_last_trades_by_instrument_and_time_get_with_http_info(self, instr >>> thread = api.public_get_last_trades_by_instrument_and_time_get_with_http_info(instrument_name, start_timestamp, end_timestamp, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param int start_timestamp: The earliest timestamp to return result for (required) :param int end_timestamp: The most recent timestamp to return result for (required) :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1390,23 +1546,26 @@ def public_get_last_trades_by_instrument_get(self, instrument_name, **kwargs): >>> thread = api.public_get_last_trades_by_instrument_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param int start_seq: The sequence number of the first trade to be returned :param int end_seq: The sequence number of the last trade to be returned :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_last_trades_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.public_get_last_trades_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.public_get_last_trades_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def public_get_last_trades_by_instrument_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Retrieve the latest trades that have occurred for a specific instrument. # noqa: E501 @@ -1416,14 +1575,23 @@ def public_get_last_trades_by_instrument_get_with_http_info(self, instrument_nam >>> thread = api.public_get_last_trades_by_instrument_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param int start_seq: The sequence number of the first trade to be returned :param int end_seq: The sequence number of the last trade to be returned :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1504,19 +1672,22 @@ def public_get_order_book_get(self, instrument_name, **kwargs): # noqa: E501 >>> thread = api.public_get_order_book_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: The instrument name for which to retrieve the order book, see [`getinstruments`](#getinstruments) to obtain instrument names. (required) :param float depth: The number of entries to return for bids and asks. + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_order_book_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.public_get_order_book_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.public_get_order_book_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def public_get_order_book_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Retrieves the order book, along with other market values for a given instrument. # noqa: E501 @@ -1526,10 +1697,19 @@ def public_get_order_book_get_with_http_info(self, instrument_name, **kwargs): >>> thread = api.public_get_order_book_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: The instrument name for which to retrieve the order book, see [`getinstruments`](#getinstruments) to obtain instrument names. (required) :param float depth: The number of entries to return for bids and asks. - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1602,17 +1782,20 @@ def public_get_trade_volumes_get(self, **kwargs): # noqa: E501 >>> thread = api.public_get_trade_volumes_get(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_trade_volumes_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.public_get_trade_volumes_get_with_http_info(**kwargs) # noqa: E501 - return data + return self.public_get_trade_volumes_get_with_http_info(**kwargs) # noqa: E501 def public_get_trade_volumes_get_with_http_info(self, **kwargs): # noqa: E501 """Retrieves aggregated 24h trade volumes for different instrument types and currencies. # noqa: E501 @@ -1622,8 +1805,17 @@ def public_get_trade_volumes_get_with_http_info(self, **kwargs): # noqa: E501 >>> thread = api.public_get_trade_volumes_get_with_http_info(async_req=True) >>> result = thread.get() - :param async_req bool - :return: object + :param async_req bool: execute request asynchronously + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1688,20 +1880,23 @@ def public_get_tradingview_chart_data_get(self, instrument_name, start_timestamp >>> thread = api.public_get_tradingview_chart_data_get(instrument_name, start_timestamp, end_timestamp, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param int start_timestamp: The earliest timestamp to return result for (required) :param int end_timestamp: The most recent timestamp to return result for (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_tradingview_chart_data_get_with_http_info(instrument_name, start_timestamp, end_timestamp, **kwargs) # noqa: E501 - else: - (data) = self.public_get_tradingview_chart_data_get_with_http_info(instrument_name, start_timestamp, end_timestamp, **kwargs) # noqa: E501 - return data + return self.public_get_tradingview_chart_data_get_with_http_info(instrument_name, start_timestamp, end_timestamp, **kwargs) # noqa: E501 def public_get_tradingview_chart_data_get_with_http_info(self, instrument_name, start_timestamp, end_timestamp, **kwargs): # noqa: E501 """Publicly available market data used to generate a TradingView candle chart. # noqa: E501 @@ -1711,11 +1906,20 @@ def public_get_tradingview_chart_data_get_with_http_info(self, instrument_name, >>> thread = api.public_get_tradingview_chart_data_get_with_http_info(instrument_name, start_timestamp, end_timestamp, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param int start_timestamp: The earliest timestamp to return result for (required) :param int end_timestamp: The most recent timestamp to return result for (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1798,18 +2002,21 @@ def public_ticker_get(self, instrument_name, **kwargs): # noqa: E501 >>> thread = api.public_ticker_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_ticker_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.public_ticker_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.public_ticker_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def public_ticker_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Get ticker for an instrument. # noqa: E501 @@ -1819,9 +2026,18 @@ def public_ticker_get_with_http_info(self, instrument_name, **kwargs): # noqa: >>> thread = api.public_ticker_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ diff --git a/python/openapi_client/api/private_api.py b/python/openapi_client/api/private_api.py index 013bae7..f849a88 100644 --- a/python/openapi_client/api/private_api.py +++ b/python/openapi_client/api/private_api.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ @@ -44,22 +44,25 @@ def private_add_to_address_book_get(self, currency, type, address, name, **kwarg >>> thread = api.private_add_to_address_book_get(currency, type, address, name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Address book type (required) :param str address: Address in currency format, it must be in address book (required) :param str name: Name of address book entry (required) :param str tfa: TFA code, required when TFA is enabled for current account + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_add_to_address_book_get_with_http_info(currency, type, address, name, **kwargs) # noqa: E501 - else: - (data) = self.private_add_to_address_book_get_with_http_info(currency, type, address, name, **kwargs) # noqa: E501 - return data + return self.private_add_to_address_book_get_with_http_info(currency, type, address, name, **kwargs) # noqa: E501 def private_add_to_address_book_get_with_http_info(self, currency, type, address, name, **kwargs): # noqa: E501 """Adds new entry to address book of given type # noqa: E501 @@ -69,13 +72,22 @@ def private_add_to_address_book_get_with_http_info(self, currency, type, address >>> thread = api.private_add_to_address_book_get_with_http_info(currency, type, address, name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Address book type (required) :param str address: Address in currency format, it must be in address book (required) :param str name: Name of address book entry (required) :param str tfa: TFA code, required when TFA is enabled for current account - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -166,7 +178,7 @@ def private_buy_get(self, instrument_name, amount, **kwargs): # noqa: E501 >>> thread = api.private_buy_get(instrument_name, amount, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param float amount: It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH (required) :param str type: The order type, default: `\"limit\"` @@ -179,16 +191,19 @@ def private_buy_get(self, instrument_name, amount, **kwargs): # noqa: E501 :param float stop_price: Stop price, required for stop limit orders (Only for stop orders) :param str trigger: Defines trigger type, required for `\"stop_limit\"` order type :param str advanced: Advanced option order type. (Only for options) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_buy_get_with_http_info(instrument_name, amount, **kwargs) # noqa: E501 - else: - (data) = self.private_buy_get_with_http_info(instrument_name, amount, **kwargs) # noqa: E501 - return data + return self.private_buy_get_with_http_info(instrument_name, amount, **kwargs) # noqa: E501 def private_buy_get_with_http_info(self, instrument_name, amount, **kwargs): # noqa: E501 """Places a buy order for an instrument. # noqa: E501 @@ -198,7 +213,7 @@ def private_buy_get_with_http_info(self, instrument_name, amount, **kwargs): # >>> thread = api.private_buy_get_with_http_info(instrument_name, amount, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param float amount: It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH (required) :param str type: The order type, default: `\"limit\"` @@ -211,7 +226,16 @@ def private_buy_get_with_http_info(self, instrument_name, amount, **kwargs): # :param float stop_price: Stop price, required for stop limit orders (Only for stop orders) :param str trigger: Defines trigger type, required for `\"stop_limit\"` order type :param str advanced: Advanced option order type. (Only for options) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -308,20 +332,23 @@ def private_cancel_all_by_currency_get(self, currency, **kwargs): # noqa: E501 >>> thread = api.private_cancel_all_by_currency_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered :param str type: Order type - limit, stop or all, default - `all` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_cancel_all_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.private_cancel_all_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.private_cancel_all_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 def private_cancel_all_by_currency_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Cancels all orders by currency, optionally filtered by instrument kind and/or order type. # noqa: E501 @@ -331,11 +358,20 @@ def private_cancel_all_by_currency_get_with_http_info(self, currency, **kwargs): >>> thread = api.private_cancel_all_by_currency_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered :param str type: Order type - limit, stop or all, default - `all` - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -410,19 +446,22 @@ def private_cancel_all_by_instrument_get(self, instrument_name, **kwargs): # no >>> thread = api.private_cancel_all_by_instrument_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param str type: Order type - limit, stop or all, default - `all` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_cancel_all_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.private_cancel_all_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.private_cancel_all_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def private_cancel_all_by_instrument_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Cancels all orders by instrument, optionally filtered by order type. # noqa: E501 @@ -432,10 +471,19 @@ def private_cancel_all_by_instrument_get_with_http_info(self, instrument_name, * >>> thread = api.private_cancel_all_by_instrument_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param str type: Order type - limit, stop or all, default - `all` - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -508,17 +556,20 @@ def private_cancel_all_get(self, **kwargs): # noqa: E501 >>> thread = api.private_cancel_all_get(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_cancel_all_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.private_cancel_all_get_with_http_info(**kwargs) # noqa: E501 - return data + return self.private_cancel_all_get_with_http_info(**kwargs) # noqa: E501 def private_cancel_all_get_with_http_info(self, **kwargs): # noqa: E501 """This method cancels all users orders and stop orders within all currencies and instrument kinds. # noqa: E501 @@ -528,8 +579,17 @@ def private_cancel_all_get_with_http_info(self, **kwargs): # noqa: E501 >>> thread = api.private_cancel_all_get_with_http_info(async_req=True) >>> result = thread.get() - :param async_req bool - :return: object + :param async_req bool: execute request asynchronously + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -594,18 +654,21 @@ def private_cancel_get(self, order_id, **kwargs): # noqa: E501 >>> thread = api.private_cancel_get(order_id, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str order_id: The order id (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_cancel_get_with_http_info(order_id, **kwargs) # noqa: E501 - else: - (data) = self.private_cancel_get_with_http_info(order_id, **kwargs) # noqa: E501 - return data + return self.private_cancel_get_with_http_info(order_id, **kwargs) # noqa: E501 def private_cancel_get_with_http_info(self, order_id, **kwargs): # noqa: E501 """Cancel an order, specified by order id # noqa: E501 @@ -615,9 +678,18 @@ def private_cancel_get_with_http_info(self, order_id, **kwargs): # noqa: E501 >>> thread = api.private_cancel_get_with_http_info(order_id, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str order_id: The order id (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -688,20 +760,23 @@ def private_cancel_transfer_by_id_get(self, currency, id, **kwargs): # noqa: E5 >>> thread = api.private_cancel_transfer_by_id_get(currency, id, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param int id: Id of transfer (required) :param str tfa: TFA code, required when TFA is enabled for current account + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_cancel_transfer_by_id_get_with_http_info(currency, id, **kwargs) # noqa: E501 - else: - (data) = self.private_cancel_transfer_by_id_get_with_http_info(currency, id, **kwargs) # noqa: E501 - return data + return self.private_cancel_transfer_by_id_get_with_http_info(currency, id, **kwargs) # noqa: E501 def private_cancel_transfer_by_id_get_with_http_info(self, currency, id, **kwargs): # noqa: E501 """Cancel transfer # noqa: E501 @@ -711,11 +786,20 @@ def private_cancel_transfer_by_id_get_with_http_info(self, currency, id, **kwarg >>> thread = api.private_cancel_transfer_by_id_get_with_http_info(currency, id, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param int id: Id of transfer (required) :param str tfa: TFA code, required when TFA is enabled for current account - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -794,19 +878,22 @@ def private_cancel_withdrawal_get(self, currency, id, **kwargs): # noqa: E501 >>> thread = api.private_cancel_withdrawal_get(currency, id, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param float id: The withdrawal id (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_cancel_withdrawal_get_with_http_info(currency, id, **kwargs) # noqa: E501 - else: - (data) = self.private_cancel_withdrawal_get_with_http_info(currency, id, **kwargs) # noqa: E501 - return data + return self.private_cancel_withdrawal_get_with_http_info(currency, id, **kwargs) # noqa: E501 def private_cancel_withdrawal_get_with_http_info(self, currency, id, **kwargs): # noqa: E501 """Cancels withdrawal request # noqa: E501 @@ -816,10 +903,19 @@ def private_cancel_withdrawal_get_with_http_info(self, currency, id, **kwargs): >>> thread = api.private_cancel_withdrawal_get_with_http_info(currency, id, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param float id: The withdrawal id (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -896,19 +992,22 @@ def private_change_subaccount_name_get(self, sid, name, **kwargs): # noqa: E501 >>> thread = api.private_change_subaccount_name_get(sid, name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param int sid: The user id for the subaccount (required) :param str name: The new user name (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_change_subaccount_name_get_with_http_info(sid, name, **kwargs) # noqa: E501 - else: - (data) = self.private_change_subaccount_name_get_with_http_info(sid, name, **kwargs) # noqa: E501 - return data + return self.private_change_subaccount_name_get_with_http_info(sid, name, **kwargs) # noqa: E501 def private_change_subaccount_name_get_with_http_info(self, sid, name, **kwargs): # noqa: E501 """Change the user name for a subaccount # noqa: E501 @@ -918,10 +1017,19 @@ def private_change_subaccount_name_get_with_http_info(self, sid, name, **kwargs) >>> thread = api.private_change_subaccount_name_get_with_http_info(sid, name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param int sid: The user id for the subaccount (required) :param str name: The new user name (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -998,20 +1106,23 @@ def private_close_position_get(self, instrument_name, type, **kwargs): # noqa: >>> thread = api.private_close_position_get(instrument_name, type, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param str type: The order type (required) :param float price: Optional price for limit order. + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_close_position_get_with_http_info(instrument_name, type, **kwargs) # noqa: E501 - else: - (data) = self.private_close_position_get_with_http_info(instrument_name, type, **kwargs) # noqa: E501 - return data + return self.private_close_position_get_with_http_info(instrument_name, type, **kwargs) # noqa: E501 def private_close_position_get_with_http_info(self, instrument_name, type, **kwargs): # noqa: E501 """Makes closing position reduce only order . # noqa: E501 @@ -1021,11 +1132,20 @@ def private_close_position_get_with_http_info(self, instrument_name, type, **kwa >>> thread = api.private_close_position_get_with_http_info(instrument_name, type, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param str type: The order type (required) :param float price: Optional price for limit order. - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1104,18 +1224,21 @@ def private_create_deposit_address_get(self, currency, **kwargs): # noqa: E501 >>> thread = api.private_create_deposit_address_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_create_deposit_address_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.private_create_deposit_address_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.private_create_deposit_address_get_with_http_info(currency, **kwargs) # noqa: E501 def private_create_deposit_address_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Creates deposit address in currency # noqa: E501 @@ -1125,9 +1248,18 @@ def private_create_deposit_address_get_with_http_info(self, currency, **kwargs): >>> thread = api.private_create_deposit_address_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1198,17 +1330,20 @@ def private_create_subaccount_get(self, **kwargs): # noqa: E501 >>> thread = api.private_create_subaccount_get(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_create_subaccount_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.private_create_subaccount_get_with_http_info(**kwargs) # noqa: E501 - return data + return self.private_create_subaccount_get_with_http_info(**kwargs) # noqa: E501 def private_create_subaccount_get_with_http_info(self, **kwargs): # noqa: E501 """Create a new subaccount # noqa: E501 @@ -1218,8 +1353,17 @@ def private_create_subaccount_get_with_http_info(self, **kwargs): # noqa: E501 >>> thread = api.private_create_subaccount_get_with_http_info(async_req=True) >>> result = thread.get() - :param async_req bool - :return: object + :param async_req bool: execute request asynchronously + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1284,18 +1428,21 @@ def private_disable_tfa_for_subaccount_get(self, sid, **kwargs): # noqa: E501 >>> thread = api.private_disable_tfa_for_subaccount_get(sid, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param int sid: The user id for the subaccount (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_disable_tfa_for_subaccount_get_with_http_info(sid, **kwargs) # noqa: E501 - else: - (data) = self.private_disable_tfa_for_subaccount_get_with_http_info(sid, **kwargs) # noqa: E501 - return data + return self.private_disable_tfa_for_subaccount_get_with_http_info(sid, **kwargs) # noqa: E501 def private_disable_tfa_for_subaccount_get_with_http_info(self, sid, **kwargs): # noqa: E501 """Disable two factor authentication for a subaccount. # noqa: E501 @@ -1305,9 +1452,18 @@ def private_disable_tfa_for_subaccount_get_with_http_info(self, sid, **kwargs): >>> thread = api.private_disable_tfa_for_subaccount_get_with_http_info(sid, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param int sid: The user id for the subaccount (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1378,19 +1534,22 @@ def private_disable_tfa_with_recovery_code_get(self, password, code, **kwargs): >>> thread = api.private_disable_tfa_with_recovery_code_get(password, code, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str password: The password for the subaccount (required) :param str code: One time recovery code (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_disable_tfa_with_recovery_code_get_with_http_info(password, code, **kwargs) # noqa: E501 - else: - (data) = self.private_disable_tfa_with_recovery_code_get_with_http_info(password, code, **kwargs) # noqa: E501 - return data + return self.private_disable_tfa_with_recovery_code_get_with_http_info(password, code, **kwargs) # noqa: E501 def private_disable_tfa_with_recovery_code_get_with_http_info(self, password, code, **kwargs): # noqa: E501 """Disables TFA with one time recovery code # noqa: E501 @@ -1400,10 +1559,19 @@ def private_disable_tfa_with_recovery_code_get_with_http_info(self, password, co >>> thread = api.private_disable_tfa_with_recovery_code_get_with_http_info(password, code, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str password: The password for the subaccount (required) :param str code: One time recovery code (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1480,23 +1648,26 @@ def private_edit_get(self, order_id, amount, price, **kwargs): # noqa: E501 >>> thread = api.private_edit_get(order_id, amount, price, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str order_id: The order id (required) :param float amount: It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH (required) :param float price:

The order price in base currency.

When editing an option order with advanced=usd, the field price should be the option price value in USD.

When editing an option order with advanced=implv, the field price should be a value of implied volatility in percentages. For example, price=100, means implied volatility of 100%

(required) :param bool post_only:

If true, the order is considered post-only. If the new price would cause the order to be filled immediately (as taker), the price will be changed to be just below the bid.

Only valid in combination with time_in_force=`\"good_til_cancelled\"`

:param str advanced: Advanced option order type. If you have posted an advanced option order, it is necessary to re-supply this parameter when editing it (Only for options) :param float stop_price: Stop price, required for stop limit orders (Only for stop orders) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_edit_get_with_http_info(order_id, amount, price, **kwargs) # noqa: E501 - else: - (data) = self.private_edit_get_with_http_info(order_id, amount, price, **kwargs) # noqa: E501 - return data + return self.private_edit_get_with_http_info(order_id, amount, price, **kwargs) # noqa: E501 def private_edit_get_with_http_info(self, order_id, amount, price, **kwargs): # noqa: E501 """Change price, amount and/or other properties of an order. # noqa: E501 @@ -1506,14 +1677,23 @@ def private_edit_get_with_http_info(self, order_id, amount, price, **kwargs): # >>> thread = api.private_edit_get_with_http_info(order_id, amount, price, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str order_id: The order id (required) :param float amount: It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH (required) :param float price:

The order price in base currency.

When editing an option order with advanced=usd, the field price should be the option price value in USD.

When editing an option order with advanced=implv, the field price should be a value of implied volatility in percentages. For example, price=100, means implied volatility of 100%

(required) :param bool post_only:

If true, the order is considered post-only. If the new price would cause the order to be filled immediately (as taker), the price will be changed to be just below the bid.

Only valid in combination with time_in_force=`\"good_til_cancelled\"`

:param str advanced: Advanced option order type. If you have posted an advanced option order, it is necessary to re-supply this parameter when editing it (Only for options) :param float stop_price: Stop price, required for stop limit orders (Only for stop orders) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1602,19 +1782,22 @@ def private_get_account_summary_get(self, currency, **kwargs): # noqa: E501 >>> thread = api.private_get_account_summary_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param bool extended: Include additional fields + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_account_summary_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.private_get_account_summary_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.private_get_account_summary_get_with_http_info(currency, **kwargs) # noqa: E501 def private_get_account_summary_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieves user account summary. # noqa: E501 @@ -1624,10 +1807,19 @@ def private_get_account_summary_get_with_http_info(self, currency, **kwargs): # >>> thread = api.private_get_account_summary_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param bool extended: Include additional fields - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1700,19 +1892,22 @@ def private_get_address_book_get(self, currency, type, **kwargs): # noqa: E501 >>> thread = api.private_get_address_book_get(currency, type, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Address book type (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_address_book_get_with_http_info(currency, type, **kwargs) # noqa: E501 - else: - (data) = self.private_get_address_book_get_with_http_info(currency, type, **kwargs) # noqa: E501 - return data + return self.private_get_address_book_get_with_http_info(currency, type, **kwargs) # noqa: E501 def private_get_address_book_get_with_http_info(self, currency, type, **kwargs): # noqa: E501 """Retrieves address book of given type # noqa: E501 @@ -1722,10 +1917,19 @@ def private_get_address_book_get_with_http_info(self, currency, type, **kwargs): >>> thread = api.private_get_address_book_get_with_http_info(currency, type, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Address book type (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1802,18 +2006,21 @@ def private_get_current_deposit_address_get(self, currency, **kwargs): # noqa: >>> thread = api.private_get_current_deposit_address_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_current_deposit_address_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.private_get_current_deposit_address_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.private_get_current_deposit_address_get_with_http_info(currency, **kwargs) # noqa: E501 def private_get_current_deposit_address_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieve deposit address for currency # noqa: E501 @@ -1823,9 +2030,18 @@ def private_get_current_deposit_address_get_with_http_info(self, currency, **kwa >>> thread = api.private_get_current_deposit_address_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1896,20 +2112,23 @@ def private_get_deposits_get(self, currency, **kwargs): # noqa: E501 >>> thread = api.private_get_deposits_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param int count: Number of requested items, default - `10` :param int offset: The offset for pagination, default - `0` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_deposits_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.private_get_deposits_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.private_get_deposits_get_with_http_info(currency, **kwargs) # noqa: E501 def private_get_deposits_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieve the latest users deposits # noqa: E501 @@ -1919,11 +2138,20 @@ def private_get_deposits_get_with_http_info(self, currency, **kwargs): # noqa: >>> thread = api.private_get_deposits_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param int count: Number of requested items, default - `10` :param int offset: The offset for pagination, default - `0` - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1998,17 +2226,20 @@ def private_get_email_language_get(self, **kwargs): # noqa: E501 >>> thread = api.private_get_email_language_get(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_email_language_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.private_get_email_language_get_with_http_info(**kwargs) # noqa: E501 - return data + return self.private_get_email_language_get_with_http_info(**kwargs) # noqa: E501 def private_get_email_language_get_with_http_info(self, **kwargs): # noqa: E501 """Retrieves the language to be used for emails. # noqa: E501 @@ -2018,8 +2249,17 @@ def private_get_email_language_get_with_http_info(self, **kwargs): # noqa: E501 >>> thread = api.private_get_email_language_get_with_http_info(async_req=True) >>> result = thread.get() - :param async_req bool - :return: object + :param async_req bool: execute request asynchronously + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -2084,20 +2324,23 @@ def private_get_margins_get(self, instrument_name, amount, price, **kwargs): # >>> thread = api.private_get_margins_get(instrument_name, amount, price, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param float amount: Amount, integer for future, float for option. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH. (required) :param float price: Price (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_margins_get_with_http_info(instrument_name, amount, price, **kwargs) # noqa: E501 - else: - (data) = self.private_get_margins_get_with_http_info(instrument_name, amount, price, **kwargs) # noqa: E501 - return data + return self.private_get_margins_get_with_http_info(instrument_name, amount, price, **kwargs) # noqa: E501 def private_get_margins_get_with_http_info(self, instrument_name, amount, price, **kwargs): # noqa: E501 """Get margins for given instrument, amount and price. # noqa: E501 @@ -2107,11 +2350,20 @@ def private_get_margins_get_with_http_info(self, instrument_name, amount, price, >>> thread = api.private_get_margins_get_with_http_info(instrument_name, amount, price, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param float amount: Amount, integer for future, float for option. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH. (required) :param float price: Price (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -2194,17 +2446,20 @@ def private_get_new_announcements_get(self, **kwargs): # noqa: E501 >>> thread = api.private_get_new_announcements_get(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_new_announcements_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.private_get_new_announcements_get_with_http_info(**kwargs) # noqa: E501 - return data + return self.private_get_new_announcements_get_with_http_info(**kwargs) # noqa: E501 def private_get_new_announcements_get_with_http_info(self, **kwargs): # noqa: E501 """Retrieves announcements that have not been marked read by the user. # noqa: E501 @@ -2214,8 +2469,17 @@ def private_get_new_announcements_get_with_http_info(self, **kwargs): # noqa: E >>> thread = api.private_get_new_announcements_get_with_http_info(async_req=True) >>> result = thread.get() - :param async_req bool - :return: object + :param async_req bool: execute request asynchronously + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -2280,20 +2544,23 @@ def private_get_open_orders_by_currency_get(self, currency, **kwargs): # noqa: >>> thread = api.private_get_open_orders_by_currency_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered :param str type: Order type, default - `all` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_open_orders_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.private_get_open_orders_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.private_get_open_orders_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 def private_get_open_orders_by_currency_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieves list of user's open orders. # noqa: E501 @@ -2303,11 +2570,20 @@ def private_get_open_orders_by_currency_get_with_http_info(self, currency, **kwa >>> thread = api.private_get_open_orders_by_currency_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered :param str type: Order type, default - `all` - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -2382,19 +2658,22 @@ def private_get_open_orders_by_instrument_get(self, instrument_name, **kwargs): >>> thread = api.private_get_open_orders_by_instrument_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param str type: Order type, default - `all` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_open_orders_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.private_get_open_orders_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.private_get_open_orders_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def private_get_open_orders_by_instrument_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Retrieves list of user's open orders within given Instrument. # noqa: E501 @@ -2404,10 +2683,19 @@ def private_get_open_orders_by_instrument_get_with_http_info(self, instrument_na >>> thread = api.private_get_open_orders_by_instrument_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param str type: Order type, default - `all` - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -2480,23 +2768,26 @@ def private_get_order_history_by_currency_get(self, currency, **kwargs): # noqa >>> thread = api.private_get_order_history_by_currency_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered :param int count: Number of requested items, default - `20` :param int offset: The offset for pagination, default - `0` :param bool include_old: Include in result orders older than 2 days, default - `false` :param bool include_unfilled: Include in result fully unfilled closed orders, default - `false` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_order_history_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.private_get_order_history_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.private_get_order_history_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 def private_get_order_history_by_currency_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieves history of orders that have been partially or fully filled. # noqa: E501 @@ -2506,14 +2797,23 @@ def private_get_order_history_by_currency_get_with_http_info(self, currency, **k >>> thread = api.private_get_order_history_by_currency_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered :param int count: Number of requested items, default - `20` :param int offset: The offset for pagination, default - `0` :param bool include_old: Include in result orders older than 2 days, default - `false` :param bool include_unfilled: Include in result fully unfilled closed orders, default - `false` - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -2594,22 +2894,25 @@ def private_get_order_history_by_instrument_get(self, instrument_name, **kwargs) >>> thread = api.private_get_order_history_by_instrument_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param int count: Number of requested items, default - `20` :param int offset: The offset for pagination, default - `0` :param bool include_old: Include in result orders older than 2 days, default - `false` :param bool include_unfilled: Include in result fully unfilled closed orders, default - `false` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_order_history_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.private_get_order_history_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.private_get_order_history_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def private_get_order_history_by_instrument_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Retrieves history of orders that have been partially or fully filled. # noqa: E501 @@ -2619,13 +2922,22 @@ def private_get_order_history_by_instrument_get_with_http_info(self, instrument_ >>> thread = api.private_get_order_history_by_instrument_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param int count: Number of requested items, default - `20` :param int offset: The offset for pagination, default - `0` :param bool include_old: Include in result orders older than 2 days, default - `false` :param bool include_unfilled: Include in result fully unfilled closed orders, default - `false` - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -2704,18 +3016,21 @@ def private_get_order_margin_by_ids_get(self, ids, **kwargs): # noqa: E501 >>> thread = api.private_get_order_margin_by_ids_get(ids, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param list[str] ids: Ids of orders (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_order_margin_by_ids_get_with_http_info(ids, **kwargs) # noqa: E501 - else: - (data) = self.private_get_order_margin_by_ids_get_with_http_info(ids, **kwargs) # noqa: E501 - return data + return self.private_get_order_margin_by_ids_get_with_http_info(ids, **kwargs) # noqa: E501 def private_get_order_margin_by_ids_get_with_http_info(self, ids, **kwargs): # noqa: E501 """Retrieves initial margins of given orders # noqa: E501 @@ -2725,9 +3040,18 @@ def private_get_order_margin_by_ids_get_with_http_info(self, ids, **kwargs): # >>> thread = api.private_get_order_margin_by_ids_get_with_http_info(ids, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param list[str] ids: Ids of orders (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -2799,18 +3123,21 @@ def private_get_order_state_get(self, order_id, **kwargs): # noqa: E501 >>> thread = api.private_get_order_state_get(order_id, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str order_id: The order id (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_order_state_get_with_http_info(order_id, **kwargs) # noqa: E501 - else: - (data) = self.private_get_order_state_get_with_http_info(order_id, **kwargs) # noqa: E501 - return data + return self.private_get_order_state_get_with_http_info(order_id, **kwargs) # noqa: E501 def private_get_order_state_get_with_http_info(self, order_id, **kwargs): # noqa: E501 """Retrieve the current state of an order. # noqa: E501 @@ -2820,9 +3147,18 @@ def private_get_order_state_get_with_http_info(self, order_id, **kwargs): # noq >>> thread = api.private_get_order_state_get_with_http_info(order_id, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str order_id: The order id (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -2893,18 +3229,21 @@ def private_get_position_get(self, instrument_name, **kwargs): # noqa: E501 >>> thread = api.private_get_position_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_position_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.private_get_position_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.private_get_position_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def private_get_position_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Retrieve user position. # noqa: E501 @@ -2914,9 +3253,18 @@ def private_get_position_get_with_http_info(self, instrument_name, **kwargs): # >>> thread = api.private_get_position_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -2987,19 +3335,22 @@ def private_get_positions_get(self, currency, **kwargs): # noqa: E501 >>> thread = api.private_get_positions_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: (required) :param str kind: Kind filter on positions + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_positions_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.private_get_positions_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.private_get_positions_get_with_http_info(currency, **kwargs) # noqa: E501 def private_get_positions_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieve user positions. # noqa: E501 @@ -3009,10 +3360,19 @@ def private_get_positions_get_with_http_info(self, currency, **kwargs): # noqa: >>> thread = api.private_get_positions_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: (required) :param str kind: Kind filter on positions - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -3085,20 +3445,23 @@ def private_get_settlement_history_by_currency_get(self, currency, **kwargs): # >>> thread = api.private_get_settlement_history_by_currency_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Settlement type :param int count: Number of requested items, default - `20` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_settlement_history_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.private_get_settlement_history_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.private_get_settlement_history_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 def private_get_settlement_history_by_currency_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieves settlement, delivery and bankruptcy events that have affected your account. # noqa: E501 @@ -3108,11 +3471,20 @@ def private_get_settlement_history_by_currency_get_with_http_info(self, currency >>> thread = api.private_get_settlement_history_by_currency_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Settlement type :param int count: Number of requested items, default - `20` - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -3187,20 +3559,23 @@ def private_get_settlement_history_by_instrument_get(self, instrument_name, **kw >>> thread = api.private_get_settlement_history_by_instrument_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param str type: Settlement type :param int count: Number of requested items, default - `20` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_settlement_history_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.private_get_settlement_history_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.private_get_settlement_history_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def private_get_settlement_history_by_instrument_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Retrieves public settlement, delivery and bankruptcy events filtered by instrument name # noqa: E501 @@ -3210,11 +3585,20 @@ def private_get_settlement_history_by_instrument_get_with_http_info(self, instru >>> thread = api.private_get_settlement_history_by_instrument_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param str type: Settlement type :param int count: Number of requested items, default - `20` - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -3289,18 +3673,21 @@ def private_get_subaccounts_get(self, **kwargs): # noqa: E501 >>> thread = api.private_get_subaccounts_get(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param bool with_portfolio: + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_subaccounts_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.private_get_subaccounts_get_with_http_info(**kwargs) # noqa: E501 - return data + return self.private_get_subaccounts_get_with_http_info(**kwargs) # noqa: E501 def private_get_subaccounts_get_with_http_info(self, **kwargs): # noqa: E501 """Get information about subaccounts # noqa: E501 @@ -3310,9 +3697,18 @@ def private_get_subaccounts_get_with_http_info(self, **kwargs): # noqa: E501 >>> thread = api.private_get_subaccounts_get_with_http_info(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param bool with_portfolio: - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -3379,20 +3775,23 @@ def private_get_transfers_get(self, currency, **kwargs): # noqa: E501 >>> thread = api.private_get_transfers_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param int count: Number of requested items, default - `10` :param int offset: The offset for pagination, default - `0` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_transfers_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.private_get_transfers_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.private_get_transfers_get_with_http_info(currency, **kwargs) # noqa: E501 def private_get_transfers_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Adds new entry to address book of given type # noqa: E501 @@ -3402,11 +3801,20 @@ def private_get_transfers_get_with_http_info(self, currency, **kwargs): # noqa: >>> thread = api.private_get_transfers_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param int count: Number of requested items, default - `10` :param int offset: The offset for pagination, default - `0` - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -3481,7 +3889,7 @@ def private_get_user_trades_by_currency_and_time_get(self, currency, start_times >>> thread = api.private_get_user_trades_by_currency_and_time_get(currency, start_timestamp, end_timestamp, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param int start_timestamp: The earliest timestamp to return result for (required) :param int end_timestamp: The most recent timestamp to return result for (required) @@ -3489,16 +3897,19 @@ def private_get_user_trades_by_currency_and_time_get(self, currency, start_times :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_user_trades_by_currency_and_time_get_with_http_info(currency, start_timestamp, end_timestamp, **kwargs) # noqa: E501 - else: - (data) = self.private_get_user_trades_by_currency_and_time_get_with_http_info(currency, start_timestamp, end_timestamp, **kwargs) # noqa: E501 - return data + return self.private_get_user_trades_by_currency_and_time_get_with_http_info(currency, start_timestamp, end_timestamp, **kwargs) # noqa: E501 def private_get_user_trades_by_currency_and_time_get_with_http_info(self, currency, start_timestamp, end_timestamp, **kwargs): # noqa: E501 """Retrieve the latest user trades that have occurred for instruments in a specific currency symbol and within given time range. # noqa: E501 @@ -3508,7 +3919,7 @@ def private_get_user_trades_by_currency_and_time_get_with_http_info(self, curren >>> thread = api.private_get_user_trades_by_currency_and_time_get_with_http_info(currency, start_timestamp, end_timestamp, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param int start_timestamp: The earliest timestamp to return result for (required) :param int end_timestamp: The most recent timestamp to return result for (required) @@ -3516,7 +3927,16 @@ def private_get_user_trades_by_currency_and_time_get_with_http_info(self, curren :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -3607,7 +4027,7 @@ def private_get_user_trades_by_currency_get(self, currency, **kwargs): # noqa: >>> thread = api.private_get_user_trades_by_currency_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered :param str start_id: The ID number of the first trade to be returned @@ -3615,16 +4035,19 @@ def private_get_user_trades_by_currency_get(self, currency, **kwargs): # noqa: :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_user_trades_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.private_get_user_trades_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.private_get_user_trades_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 def private_get_user_trades_by_currency_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieve the latest user trades that have occurred for instruments in a specific currency symbol. # noqa: E501 @@ -3634,7 +4057,7 @@ def private_get_user_trades_by_currency_get_with_http_info(self, currency, **kwa >>> thread = api.private_get_user_trades_by_currency_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered :param str start_id: The ID number of the first trade to be returned @@ -3642,7 +4065,16 @@ def private_get_user_trades_by_currency_get_with_http_info(self, currency, **kwa :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -3725,23 +4157,26 @@ def private_get_user_trades_by_instrument_and_time_get(self, instrument_name, st >>> thread = api.private_get_user_trades_by_instrument_and_time_get(instrument_name, start_timestamp, end_timestamp, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param int start_timestamp: The earliest timestamp to return result for (required) :param int end_timestamp: The most recent timestamp to return result for (required) :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_user_trades_by_instrument_and_time_get_with_http_info(instrument_name, start_timestamp, end_timestamp, **kwargs) # noqa: E501 - else: - (data) = self.private_get_user_trades_by_instrument_and_time_get_with_http_info(instrument_name, start_timestamp, end_timestamp, **kwargs) # noqa: E501 - return data + return self.private_get_user_trades_by_instrument_and_time_get_with_http_info(instrument_name, start_timestamp, end_timestamp, **kwargs) # noqa: E501 def private_get_user_trades_by_instrument_and_time_get_with_http_info(self, instrument_name, start_timestamp, end_timestamp, **kwargs): # noqa: E501 """Retrieve the latest user trades that have occurred for a specific instrument and within given time range. # noqa: E501 @@ -3751,14 +4186,23 @@ def private_get_user_trades_by_instrument_and_time_get_with_http_info(self, inst >>> thread = api.private_get_user_trades_by_instrument_and_time_get_with_http_info(instrument_name, start_timestamp, end_timestamp, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param int start_timestamp: The earliest timestamp to return result for (required) :param int end_timestamp: The most recent timestamp to return result for (required) :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -3847,23 +4291,26 @@ def private_get_user_trades_by_instrument_get(self, instrument_name, **kwargs): >>> thread = api.private_get_user_trades_by_instrument_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param int start_seq: The sequence number of the first trade to be returned :param int end_seq: The sequence number of the last trade to be returned :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_user_trades_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.private_get_user_trades_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.private_get_user_trades_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def private_get_user_trades_by_instrument_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Retrieve the latest user trades that have occurred for a specific instrument. # noqa: E501 @@ -3873,14 +4320,23 @@ def private_get_user_trades_by_instrument_get_with_http_info(self, instrument_na >>> thread = api.private_get_user_trades_by_instrument_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param int start_seq: The sequence number of the first trade to be returned :param int end_seq: The sequence number of the last trade to be returned :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -3961,19 +4417,22 @@ def private_get_user_trades_by_order_get(self, order_id, **kwargs): # noqa: E50 >>> thread = api.private_get_user_trades_by_order_get(order_id, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str order_id: The order id (required) :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_user_trades_by_order_get_with_http_info(order_id, **kwargs) # noqa: E501 - else: - (data) = self.private_get_user_trades_by_order_get_with_http_info(order_id, **kwargs) # noqa: E501 - return data + return self.private_get_user_trades_by_order_get_with_http_info(order_id, **kwargs) # noqa: E501 def private_get_user_trades_by_order_get_with_http_info(self, order_id, **kwargs): # noqa: E501 """Retrieve the list of user trades that was created for given order # noqa: E501 @@ -3983,10 +4442,19 @@ def private_get_user_trades_by_order_get_with_http_info(self, order_id, **kwargs >>> thread = api.private_get_user_trades_by_order_get_with_http_info(order_id, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str order_id: The order id (required) :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -4059,20 +4527,23 @@ def private_get_withdrawals_get(self, currency, **kwargs): # noqa: E501 >>> thread = api.private_get_withdrawals_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param int count: Number of requested items, default - `10` :param int offset: The offset for pagination, default - `0` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_withdrawals_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.private_get_withdrawals_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.private_get_withdrawals_get_with_http_info(currency, **kwargs) # noqa: E501 def private_get_withdrawals_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieve the latest users withdrawals # noqa: E501 @@ -4082,11 +4553,20 @@ def private_get_withdrawals_get_with_http_info(self, currency, **kwargs): # noq >>> thread = api.private_get_withdrawals_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param int count: Number of requested items, default - `10` :param int offset: The offset for pagination, default - `0` - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -4161,21 +4641,24 @@ def private_remove_from_address_book_get(self, currency, type, address, **kwargs >>> thread = api.private_remove_from_address_book_get(currency, type, address, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Address book type (required) :param str address: Address in currency format, it must be in address book (required) :param str tfa: TFA code, required when TFA is enabled for current account + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_remove_from_address_book_get_with_http_info(currency, type, address, **kwargs) # noqa: E501 - else: - (data) = self.private_remove_from_address_book_get_with_http_info(currency, type, address, **kwargs) # noqa: E501 - return data + return self.private_remove_from_address_book_get_with_http_info(currency, type, address, **kwargs) # noqa: E501 def private_remove_from_address_book_get_with_http_info(self, currency, type, address, **kwargs): # noqa: E501 """Adds new entry to address book of given type # noqa: E501 @@ -4185,12 +4668,21 @@ def private_remove_from_address_book_get_with_http_info(self, currency, type, ad >>> thread = api.private_remove_from_address_book_get_with_http_info(currency, type, address, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Address book type (required) :param str address: Address in currency format, it must be in address book (required) :param str tfa: TFA code, required when TFA is enabled for current account - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -4275,7 +4767,7 @@ def private_sell_get(self, instrument_name, amount, **kwargs): # noqa: E501 >>> thread = api.private_sell_get(instrument_name, amount, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param float amount: It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH (required) :param str type: The order type, default: `\"limit\"` @@ -4288,16 +4780,19 @@ def private_sell_get(self, instrument_name, amount, **kwargs): # noqa: E501 :param float stop_price: Stop price, required for stop limit orders (Only for stop orders) :param str trigger: Defines trigger type, required for `\"stop_limit\"` order type :param str advanced: Advanced option order type. (Only for options) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_sell_get_with_http_info(instrument_name, amount, **kwargs) # noqa: E501 - else: - (data) = self.private_sell_get_with_http_info(instrument_name, amount, **kwargs) # noqa: E501 - return data + return self.private_sell_get_with_http_info(instrument_name, amount, **kwargs) # noqa: E501 def private_sell_get_with_http_info(self, instrument_name, amount, **kwargs): # noqa: E501 """Places a sell order for an instrument. # noqa: E501 @@ -4307,7 +4802,7 @@ def private_sell_get_with_http_info(self, instrument_name, amount, **kwargs): # >>> thread = api.private_sell_get_with_http_info(instrument_name, amount, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param float amount: It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH (required) :param str type: The order type, default: `\"limit\"` @@ -4320,7 +4815,16 @@ def private_sell_get_with_http_info(self, instrument_name, amount, **kwargs): # :param float stop_price: Stop price, required for stop limit orders (Only for stop orders) :param str trigger: Defines trigger type, required for `\"stop_limit\"` order type :param str advanced: Advanced option order type. (Only for options) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -4417,18 +4921,21 @@ def private_set_announcement_as_read_get(self, announcement_id, **kwargs): # no >>> thread = api.private_set_announcement_as_read_get(announcement_id, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param float announcement_id: the ID of the announcement (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_set_announcement_as_read_get_with_http_info(announcement_id, **kwargs) # noqa: E501 - else: - (data) = self.private_set_announcement_as_read_get_with_http_info(announcement_id, **kwargs) # noqa: E501 - return data + return self.private_set_announcement_as_read_get_with_http_info(announcement_id, **kwargs) # noqa: E501 def private_set_announcement_as_read_get_with_http_info(self, announcement_id, **kwargs): # noqa: E501 """Marks an announcement as read, so it will not be shown in `get_new_announcements`. # noqa: E501 @@ -4438,9 +4945,18 @@ def private_set_announcement_as_read_get_with_http_info(self, announcement_id, * >>> thread = api.private_set_announcement_as_read_get_with_http_info(announcement_id, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param float announcement_id: the ID of the announcement (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -4511,19 +5027,22 @@ def private_set_email_for_subaccount_get(self, sid, email, **kwargs): # noqa: E >>> thread = api.private_set_email_for_subaccount_get(sid, email, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param int sid: The user id for the subaccount (required) :param str email: The email address for the subaccount (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_set_email_for_subaccount_get_with_http_info(sid, email, **kwargs) # noqa: E501 - else: - (data) = self.private_set_email_for_subaccount_get_with_http_info(sid, email, **kwargs) # noqa: E501 - return data + return self.private_set_email_for_subaccount_get_with_http_info(sid, email, **kwargs) # noqa: E501 def private_set_email_for_subaccount_get_with_http_info(self, sid, email, **kwargs): # noqa: E501 """Assign an email address to a subaccount. User will receive an email with confirmation link. # noqa: E501 @@ -4533,10 +5052,19 @@ def private_set_email_for_subaccount_get_with_http_info(self, sid, email, **kwar >>> thread = api.private_set_email_for_subaccount_get_with_http_info(sid, email, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param int sid: The user id for the subaccount (required) :param str email: The email address for the subaccount (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -4613,18 +5141,21 @@ def private_set_email_language_get(self, language, **kwargs): # noqa: E501 >>> thread = api.private_set_email_language_get(language, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str language: The abbreviated language name. Valid values include `\"en\"`, `\"ko\"`, `\"zh\"` (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_set_email_language_get_with_http_info(language, **kwargs) # noqa: E501 - else: - (data) = self.private_set_email_language_get_with_http_info(language, **kwargs) # noqa: E501 - return data + return self.private_set_email_language_get_with_http_info(language, **kwargs) # noqa: E501 def private_set_email_language_get_with_http_info(self, language, **kwargs): # noqa: E501 """Changes the language to be used for emails. # noqa: E501 @@ -4634,9 +5165,18 @@ def private_set_email_language_get_with_http_info(self, language, **kwargs): # >>> thread = api.private_set_email_language_get_with_http_info(language, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str language: The abbreviated language name. Valid values include `\"en\"`, `\"ko\"`, `\"zh\"` (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -4707,19 +5247,22 @@ def private_set_password_for_subaccount_get(self, sid, password, **kwargs): # n >>> thread = api.private_set_password_for_subaccount_get(sid, password, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param int sid: The user id for the subaccount (required) :param str password: The password for the subaccount (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_set_password_for_subaccount_get_with_http_info(sid, password, **kwargs) # noqa: E501 - else: - (data) = self.private_set_password_for_subaccount_get_with_http_info(sid, password, **kwargs) # noqa: E501 - return data + return self.private_set_password_for_subaccount_get_with_http_info(sid, password, **kwargs) # noqa: E501 def private_set_password_for_subaccount_get_with_http_info(self, sid, password, **kwargs): # noqa: E501 """Set the password for the subaccount # noqa: E501 @@ -4729,10 +5272,19 @@ def private_set_password_for_subaccount_get_with_http_info(self, sid, password, >>> thread = api.private_set_password_for_subaccount_get_with_http_info(sid, password, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param int sid: The user id for the subaccount (required) :param str password: The password for the subaccount (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -4809,20 +5361,23 @@ def private_submit_transfer_to_subaccount_get(self, currency, amount, destinatio >>> thread = api.private_submit_transfer_to_subaccount_get(currency, amount, destination, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param float amount: Amount of funds to be transferred (required) :param int destination: Id of destination subaccount (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_submit_transfer_to_subaccount_get_with_http_info(currency, amount, destination, **kwargs) # noqa: E501 - else: - (data) = self.private_submit_transfer_to_subaccount_get_with_http_info(currency, amount, destination, **kwargs) # noqa: E501 - return data + return self.private_submit_transfer_to_subaccount_get_with_http_info(currency, amount, destination, **kwargs) # noqa: E501 def private_submit_transfer_to_subaccount_get_with_http_info(self, currency, amount, destination, **kwargs): # noqa: E501 """Transfer funds to a subaccount. # noqa: E501 @@ -4832,11 +5387,20 @@ def private_submit_transfer_to_subaccount_get_with_http_info(self, currency, amo >>> thread = api.private_submit_transfer_to_subaccount_get_with_http_info(currency, amount, destination, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param float amount: Amount of funds to be transferred (required) :param int destination: Id of destination subaccount (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -4919,21 +5483,24 @@ def private_submit_transfer_to_user_get(self, currency, amount, destination, **k >>> thread = api.private_submit_transfer_to_user_get(currency, amount, destination, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param float amount: Amount of funds to be transferred (required) :param str destination: Destination address from address book (required) :param str tfa: TFA code, required when TFA is enabled for current account + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_submit_transfer_to_user_get_with_http_info(currency, amount, destination, **kwargs) # noqa: E501 - else: - (data) = self.private_submit_transfer_to_user_get_with_http_info(currency, amount, destination, **kwargs) # noqa: E501 - return data + return self.private_submit_transfer_to_user_get_with_http_info(currency, amount, destination, **kwargs) # noqa: E501 def private_submit_transfer_to_user_get_with_http_info(self, currency, amount, destination, **kwargs): # noqa: E501 """Transfer funds to a another user. # noqa: E501 @@ -4943,12 +5510,21 @@ def private_submit_transfer_to_user_get_with_http_info(self, currency, amount, d >>> thread = api.private_submit_transfer_to_user_get_with_http_info(currency, amount, destination, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param float amount: Amount of funds to be transferred (required) :param str destination: Destination address from address book (required) :param str tfa: TFA code, required when TFA is enabled for current account - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -5033,19 +5609,22 @@ def private_toggle_deposit_address_creation_get(self, currency, state, **kwargs) >>> thread = api.private_toggle_deposit_address_creation_get(currency, state, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param bool state: (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_toggle_deposit_address_creation_get_with_http_info(currency, state, **kwargs) # noqa: E501 - else: - (data) = self.private_toggle_deposit_address_creation_get_with_http_info(currency, state, **kwargs) # noqa: E501 - return data + return self.private_toggle_deposit_address_creation_get_with_http_info(currency, state, **kwargs) # noqa: E501 def private_toggle_deposit_address_creation_get_with_http_info(self, currency, state, **kwargs): # noqa: E501 """Enable or disable deposit address creation # noqa: E501 @@ -5055,10 +5634,19 @@ def private_toggle_deposit_address_creation_get_with_http_info(self, currency, s >>> thread = api.private_toggle_deposit_address_creation_get_with_http_info(currency, state, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param bool state: (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -5135,19 +5723,22 @@ def private_toggle_notifications_from_subaccount_get(self, sid, state, **kwargs) >>> thread = api.private_toggle_notifications_from_subaccount_get(sid, state, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param int sid: The user id for the subaccount (required) :param bool state: enable (`true`) or disable (`false`) notifications (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_toggle_notifications_from_subaccount_get_with_http_info(sid, state, **kwargs) # noqa: E501 - else: - (data) = self.private_toggle_notifications_from_subaccount_get_with_http_info(sid, state, **kwargs) # noqa: E501 - return data + return self.private_toggle_notifications_from_subaccount_get_with_http_info(sid, state, **kwargs) # noqa: E501 def private_toggle_notifications_from_subaccount_get_with_http_info(self, sid, state, **kwargs): # noqa: E501 """Enable or disable sending of notifications for the subaccount. # noqa: E501 @@ -5157,10 +5748,19 @@ def private_toggle_notifications_from_subaccount_get_with_http_info(self, sid, s >>> thread = api.private_toggle_notifications_from_subaccount_get_with_http_info(sid, state, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param int sid: The user id for the subaccount (required) :param bool state: enable (`true`) or disable (`false`) notifications (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -5237,19 +5837,22 @@ def private_toggle_subaccount_login_get(self, sid, state, **kwargs): # noqa: E5 >>> thread = api.private_toggle_subaccount_login_get(sid, state, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param int sid: The user id for the subaccount (required) :param str state: enable or disable login. (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_toggle_subaccount_login_get_with_http_info(sid, state, **kwargs) # noqa: E501 - else: - (data) = self.private_toggle_subaccount_login_get_with_http_info(sid, state, **kwargs) # noqa: E501 - return data + return self.private_toggle_subaccount_login_get_with_http_info(sid, state, **kwargs) # noqa: E501 def private_toggle_subaccount_login_get_with_http_info(self, sid, state, **kwargs): # noqa: E501 """Enable or disable login for a subaccount. If login is disabled and a session for the subaccount exists, this session will be terminated. # noqa: E501 @@ -5259,10 +5862,19 @@ def private_toggle_subaccount_login_get_with_http_info(self, sid, state, **kwarg >>> thread = api.private_toggle_subaccount_login_get_with_http_info(sid, state, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param int sid: The user id for the subaccount (required) :param str state: enable or disable login. (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -5339,22 +5951,25 @@ def private_withdraw_get(self, currency, address, amount, **kwargs): # noqa: E5 >>> thread = api.private_withdraw_get(currency, address, amount, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str address: Address in currency format, it must be in address book (required) :param float amount: Amount of funds to be withdrawn (required) :param str priority: Withdrawal priority, optional for BTC, default: `high` :param str tfa: TFA code, required when TFA is enabled for current account + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_withdraw_get_with_http_info(currency, address, amount, **kwargs) # noqa: E501 - else: - (data) = self.private_withdraw_get_with_http_info(currency, address, amount, **kwargs) # noqa: E501 - return data + return self.private_withdraw_get_with_http_info(currency, address, amount, **kwargs) # noqa: E501 def private_withdraw_get_with_http_info(self, currency, address, amount, **kwargs): # noqa: E501 """Creates a new withdrawal request # noqa: E501 @@ -5364,13 +5979,22 @@ def private_withdraw_get_with_http_info(self, currency, address, amount, **kwarg >>> thread = api.private_withdraw_get_with_http_info(currency, address, amount, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str address: Address in currency format, it must be in address book (required) :param float amount: Amount of funds to be withdrawn (required) :param str priority: Withdrawal priority, optional for BTC, default: `high` :param str tfa: TFA code, required when TFA is enabled for current account - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ diff --git a/python/openapi_client/api/public_api.py b/python/openapi_client/api/public_api.py index dc1f7bd..483429d 100644 --- a/python/openapi_client/api/public_api.py +++ b/python/openapi_client/api/public_api.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ @@ -45,7 +45,7 @@ def public_auth_get(self, grant_type, username, password, client_id, client_secr >>> thread = api.public_auth_get(grant_type, username, password, client_id, client_secret, refresh_token, timestamp, signature, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str grant_type: Method of authentication (required) :param str username: Required for grant type `password` (required) :param str password: Required for grant type `password` (required) @@ -57,16 +57,19 @@ def public_auth_get(self, grant_type, username, password, client_id, client_secr :param str nonce: Optional for grant type `client_signature`; delivers user generated initialization vector for the server token :param str state: Will be passed back in the response :param str scope: Describes type of the access for assigned token, possible values: `connection`, `session`, `session:name`, `trade:[read, read_write, none]`, `wallet:[read, read_write, none]`, `account:[read, read_write, none]`, `expires:NUMBER` (token will expire after `NUMBER` of seconds).

**NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read``` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_auth_get_with_http_info(grant_type, username, password, client_id, client_secret, refresh_token, timestamp, signature, **kwargs) # noqa: E501 - else: - (data) = self.public_auth_get_with_http_info(grant_type, username, password, client_id, client_secret, refresh_token, timestamp, signature, **kwargs) # noqa: E501 - return data + return self.public_auth_get_with_http_info(grant_type, username, password, client_id, client_secret, refresh_token, timestamp, signature, **kwargs) # noqa: E501 def public_auth_get_with_http_info(self, grant_type, username, password, client_id, client_secret, refresh_token, timestamp, signature, **kwargs): # noqa: E501 """Authenticate # noqa: E501 @@ -77,7 +80,7 @@ def public_auth_get_with_http_info(self, grant_type, username, password, client_ >>> thread = api.public_auth_get_with_http_info(grant_type, username, password, client_id, client_secret, refresh_token, timestamp, signature, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str grant_type: Method of authentication (required) :param str username: Required for grant type `password` (required) :param str password: Required for grant type `password` (required) @@ -89,7 +92,16 @@ def public_auth_get_with_http_info(self, grant_type, username, password, client_ :param str nonce: Optional for grant type `client_signature`; delivers user generated initialization vector for the server token :param str state: Will be passed back in the response :param str scope: Describes type of the access for assigned token, possible values: `connection`, `session`, `session:name`, `trade:[read, read_write, none]`, `wallet:[read, read_write, none]`, `account:[read, read_write, none]`, `expires:NUMBER` (token will expire after `NUMBER` of seconds).

**NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read``` - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -208,17 +220,20 @@ def public_get_announcements_get(self, **kwargs): # noqa: E501 >>> thread = api.public_get_announcements_get(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_announcements_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.public_get_announcements_get_with_http_info(**kwargs) # noqa: E501 - return data + return self.public_get_announcements_get_with_http_info(**kwargs) # noqa: E501 def public_get_announcements_get_with_http_info(self, **kwargs): # noqa: E501 """Retrieves announcements from the last 30 days. # noqa: E501 @@ -228,8 +243,17 @@ def public_get_announcements_get_with_http_info(self, **kwargs): # noqa: E501 >>> thread = api.public_get_announcements_get_with_http_info(async_req=True) >>> result = thread.get() - :param async_req bool - :return: object + :param async_req bool: execute request asynchronously + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -294,19 +318,22 @@ def public_get_book_summary_by_currency_get(self, currency, **kwargs): # noqa: >>> thread = api.public_get_book_summary_by_currency_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_book_summary_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.public_get_book_summary_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.public_get_book_summary_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 def public_get_book_summary_by_currency_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieves the summary information such as open interest, 24h volume, etc. for all instruments for the currency (optionally filtered by kind). # noqa: E501 @@ -316,10 +343,19 @@ def public_get_book_summary_by_currency_get_with_http_info(self, currency, **kwa >>> thread = api.public_get_book_summary_by_currency_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -392,18 +428,21 @@ def public_get_book_summary_by_instrument_get(self, instrument_name, **kwargs): >>> thread = api.public_get_book_summary_by_instrument_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_book_summary_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.public_get_book_summary_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.public_get_book_summary_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def public_get_book_summary_by_instrument_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Retrieves the summary information such as open interest, 24h volume, etc. for a specific instrument. # noqa: E501 @@ -413,9 +452,18 @@ def public_get_book_summary_by_instrument_get_with_http_info(self, instrument_na >>> thread = api.public_get_book_summary_by_instrument_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -486,18 +534,21 @@ def public_get_contract_size_get(self, instrument_name, **kwargs): # noqa: E501 >>> thread = api.public_get_contract_size_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_contract_size_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.public_get_contract_size_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.public_get_contract_size_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def public_get_contract_size_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Retrieves contract size of provided instrument. # noqa: E501 @@ -507,9 +558,18 @@ def public_get_contract_size_get_with_http_info(self, instrument_name, **kwargs) >>> thread = api.public_get_contract_size_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -580,17 +640,20 @@ def public_get_currencies_get(self, **kwargs): # noqa: E501 >>> thread = api.public_get_currencies_get(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_currencies_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.public_get_currencies_get_with_http_info(**kwargs) # noqa: E501 - return data + return self.public_get_currencies_get_with_http_info(**kwargs) # noqa: E501 def public_get_currencies_get_with_http_info(self, **kwargs): # noqa: E501 """Retrieves all cryptocurrencies supported by the API. # noqa: E501 @@ -600,8 +663,17 @@ def public_get_currencies_get_with_http_info(self, **kwargs): # noqa: E501 >>> thread = api.public_get_currencies_get_with_http_info(async_req=True) >>> result = thread.get() - :param async_req bool - :return: object + :param async_req bool: execute request asynchronously + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -666,19 +738,22 @@ def public_get_funding_chart_data_get(self, instrument_name, **kwargs): # noqa: >>> thread = api.public_get_funding_chart_data_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param str length: Specifies time period. `8h` - 8 hours, `24h` - 24 hours + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_funding_chart_data_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.public_get_funding_chart_data_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.public_get_funding_chart_data_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def public_get_funding_chart_data_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Retrieve the latest user trades that have occurred for PERPETUAL instruments in a specific currency symbol and within given time range. # noqa: E501 @@ -688,10 +763,19 @@ def public_get_funding_chart_data_get_with_http_info(self, instrument_name, **kw >>> thread = api.public_get_funding_chart_data_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param str length: Specifies time period. `8h` - 8 hours, `24h` - 24 hours - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -764,18 +848,21 @@ def public_get_historical_volatility_get(self, currency, **kwargs): # noqa: E50 >>> thread = api.public_get_historical_volatility_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_historical_volatility_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.public_get_historical_volatility_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.public_get_historical_volatility_get_with_http_info(currency, **kwargs) # noqa: E501 def public_get_historical_volatility_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Provides information about historical volatility for given cryptocurrency. # noqa: E501 @@ -785,9 +872,18 @@ def public_get_historical_volatility_get_with_http_info(self, currency, **kwargs >>> thread = api.public_get_historical_volatility_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -858,18 +954,21 @@ def public_get_index_get(self, currency, **kwargs): # noqa: E501 >>> thread = api.public_get_index_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_index_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.public_get_index_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.public_get_index_get_with_http_info(currency, **kwargs) # noqa: E501 def public_get_index_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieves the current index price for the instruments, for the selected currency. # noqa: E501 @@ -879,9 +978,18 @@ def public_get_index_get_with_http_info(self, currency, **kwargs): # noqa: E501 >>> thread = api.public_get_index_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -952,20 +1060,23 @@ def public_get_instruments_get(self, currency, **kwargs): # noqa: E501 >>> thread = api.public_get_instruments_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered :param bool expired: Set to true to show expired instruments instead of active ones. + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_instruments_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.public_get_instruments_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.public_get_instruments_get_with_http_info(currency, **kwargs) # noqa: E501 def public_get_instruments_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieves available trading instruments. This method can be used to see which instruments are available for trading, or which instruments have existed historically. # noqa: E501 @@ -975,11 +1086,20 @@ def public_get_instruments_get_with_http_info(self, currency, **kwargs): # noqa >>> thread = api.public_get_instruments_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered :param bool expired: Set to true to show expired instruments instead of active ones. - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1054,22 +1174,25 @@ def public_get_last_settlements_by_currency_get(self, currency, **kwargs): # no >>> thread = api.public_get_last_settlements_by_currency_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Settlement type :param int count: Number of requested items, default - `20` :param str continuation: Continuation token for pagination :param int search_start_timestamp: The latest timestamp to return result for + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_last_settlements_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.public_get_last_settlements_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.public_get_last_settlements_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 def public_get_last_settlements_by_currency_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieves historical settlement, delivery and bankruptcy events coming from all instruments within given currency. # noqa: E501 @@ -1079,13 +1202,22 @@ def public_get_last_settlements_by_currency_get_with_http_info(self, currency, * >>> thread = api.public_get_last_settlements_by_currency_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Settlement type :param int count: Number of requested items, default - `20` :param str continuation: Continuation token for pagination :param int search_start_timestamp: The latest timestamp to return result for - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1164,22 +1296,25 @@ def public_get_last_settlements_by_instrument_get(self, instrument_name, **kwarg >>> thread = api.public_get_last_settlements_by_instrument_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param str type: Settlement type :param int count: Number of requested items, default - `20` :param str continuation: Continuation token for pagination :param int search_start_timestamp: The latest timestamp to return result for + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_last_settlements_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.public_get_last_settlements_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.public_get_last_settlements_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def public_get_last_settlements_by_instrument_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Retrieves historical public settlement, delivery and bankruptcy events filtered by instrument name. # noqa: E501 @@ -1189,13 +1324,22 @@ def public_get_last_settlements_by_instrument_get_with_http_info(self, instrumen >>> thread = api.public_get_last_settlements_by_instrument_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param str type: Settlement type :param int count: Number of requested items, default - `20` :param str continuation: Continuation token for pagination :param int search_start_timestamp: The latest timestamp to return result for - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1274,7 +1418,7 @@ def public_get_last_trades_by_currency_and_time_get(self, currency, start_timest >>> thread = api.public_get_last_trades_by_currency_and_time_get(currency, start_timestamp, end_timestamp, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param int start_timestamp: The earliest timestamp to return result for (required) :param int end_timestamp: The most recent timestamp to return result for (required) @@ -1282,16 +1426,19 @@ def public_get_last_trades_by_currency_and_time_get(self, currency, start_timest :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_last_trades_by_currency_and_time_get_with_http_info(currency, start_timestamp, end_timestamp, **kwargs) # noqa: E501 - else: - (data) = self.public_get_last_trades_by_currency_and_time_get_with_http_info(currency, start_timestamp, end_timestamp, **kwargs) # noqa: E501 - return data + return self.public_get_last_trades_by_currency_and_time_get_with_http_info(currency, start_timestamp, end_timestamp, **kwargs) # noqa: E501 def public_get_last_trades_by_currency_and_time_get_with_http_info(self, currency, start_timestamp, end_timestamp, **kwargs): # noqa: E501 """Retrieve the latest trades that have occurred for instruments in a specific currency symbol and within given time range. # noqa: E501 @@ -1301,7 +1448,7 @@ def public_get_last_trades_by_currency_and_time_get_with_http_info(self, currenc >>> thread = api.public_get_last_trades_by_currency_and_time_get_with_http_info(currency, start_timestamp, end_timestamp, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param int start_timestamp: The earliest timestamp to return result for (required) :param int end_timestamp: The most recent timestamp to return result for (required) @@ -1309,7 +1456,16 @@ def public_get_last_trades_by_currency_and_time_get_with_http_info(self, currenc :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1400,7 +1556,7 @@ def public_get_last_trades_by_currency_get(self, currency, **kwargs): # noqa: E >>> thread = api.public_get_last_trades_by_currency_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered :param str start_id: The ID number of the first trade to be returned @@ -1408,16 +1564,19 @@ def public_get_last_trades_by_currency_get(self, currency, **kwargs): # noqa: E :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_last_trades_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.public_get_last_trades_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.public_get_last_trades_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 def public_get_last_trades_by_currency_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieve the latest trades that have occurred for instruments in a specific currency symbol. # noqa: E501 @@ -1427,7 +1586,7 @@ def public_get_last_trades_by_currency_get_with_http_info(self, currency, **kwar >>> thread = api.public_get_last_trades_by_currency_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered :param str start_id: The ID number of the first trade to be returned @@ -1435,7 +1594,16 @@ def public_get_last_trades_by_currency_get_with_http_info(self, currency, **kwar :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1518,23 +1686,26 @@ def public_get_last_trades_by_instrument_and_time_get(self, instrument_name, sta >>> thread = api.public_get_last_trades_by_instrument_and_time_get(instrument_name, start_timestamp, end_timestamp, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param int start_timestamp: The earliest timestamp to return result for (required) :param int end_timestamp: The most recent timestamp to return result for (required) :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_last_trades_by_instrument_and_time_get_with_http_info(instrument_name, start_timestamp, end_timestamp, **kwargs) # noqa: E501 - else: - (data) = self.public_get_last_trades_by_instrument_and_time_get_with_http_info(instrument_name, start_timestamp, end_timestamp, **kwargs) # noqa: E501 - return data + return self.public_get_last_trades_by_instrument_and_time_get_with_http_info(instrument_name, start_timestamp, end_timestamp, **kwargs) # noqa: E501 def public_get_last_trades_by_instrument_and_time_get_with_http_info(self, instrument_name, start_timestamp, end_timestamp, **kwargs): # noqa: E501 """Retrieve the latest trades that have occurred for a specific instrument and within given time range. # noqa: E501 @@ -1544,14 +1715,23 @@ def public_get_last_trades_by_instrument_and_time_get_with_http_info(self, instr >>> thread = api.public_get_last_trades_by_instrument_and_time_get_with_http_info(instrument_name, start_timestamp, end_timestamp, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param int start_timestamp: The earliest timestamp to return result for (required) :param int end_timestamp: The most recent timestamp to return result for (required) :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1640,23 +1820,26 @@ def public_get_last_trades_by_instrument_get(self, instrument_name, **kwargs): >>> thread = api.public_get_last_trades_by_instrument_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param int start_seq: The sequence number of the first trade to be returned :param int end_seq: The sequence number of the last trade to be returned :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_last_trades_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.public_get_last_trades_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.public_get_last_trades_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def public_get_last_trades_by_instrument_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Retrieve the latest trades that have occurred for a specific instrument. # noqa: E501 @@ -1666,14 +1849,23 @@ def public_get_last_trades_by_instrument_get_with_http_info(self, instrument_nam >>> thread = api.public_get_last_trades_by_instrument_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param int start_seq: The sequence number of the first trade to be returned :param int end_seq: The sequence number of the last trade to be returned :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1754,19 +1946,22 @@ def public_get_order_book_get(self, instrument_name, **kwargs): # noqa: E501 >>> thread = api.public_get_order_book_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: The instrument name for which to retrieve the order book, see [`getinstruments`](#getinstruments) to obtain instrument names. (required) :param float depth: The number of entries to return for bids and asks. + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_order_book_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.public_get_order_book_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.public_get_order_book_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def public_get_order_book_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Retrieves the order book, along with other market values for a given instrument. # noqa: E501 @@ -1776,10 +1971,19 @@ def public_get_order_book_get_with_http_info(self, instrument_name, **kwargs): >>> thread = api.public_get_order_book_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: The instrument name for which to retrieve the order book, see [`getinstruments`](#getinstruments) to obtain instrument names. (required) :param float depth: The number of entries to return for bids and asks. - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1852,17 +2056,20 @@ def public_get_time_get(self, **kwargs): # noqa: E501 >>> thread = api.public_get_time_get(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_time_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.public_get_time_get_with_http_info(**kwargs) # noqa: E501 - return data + return self.public_get_time_get_with_http_info(**kwargs) # noqa: E501 def public_get_time_get_with_http_info(self, **kwargs): # noqa: E501 """Retrieves the current time (in milliseconds). This API endpoint can be used to check the clock skew between your software and Deribit's systems. # noqa: E501 @@ -1872,8 +2079,17 @@ def public_get_time_get_with_http_info(self, **kwargs): # noqa: E501 >>> thread = api.public_get_time_get_with_http_info(async_req=True) >>> result = thread.get() - :param async_req bool - :return: object + :param async_req bool: execute request asynchronously + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1938,17 +2154,20 @@ def public_get_trade_volumes_get(self, **kwargs): # noqa: E501 >>> thread = api.public_get_trade_volumes_get(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_trade_volumes_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.public_get_trade_volumes_get_with_http_info(**kwargs) # noqa: E501 - return data + return self.public_get_trade_volumes_get_with_http_info(**kwargs) # noqa: E501 def public_get_trade_volumes_get_with_http_info(self, **kwargs): # noqa: E501 """Retrieves aggregated 24h trade volumes for different instrument types and currencies. # noqa: E501 @@ -1958,8 +2177,17 @@ def public_get_trade_volumes_get_with_http_info(self, **kwargs): # noqa: E501 >>> thread = api.public_get_trade_volumes_get_with_http_info(async_req=True) >>> result = thread.get() - :param async_req bool - :return: object + :param async_req bool: execute request asynchronously + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -2024,20 +2252,23 @@ def public_get_tradingview_chart_data_get(self, instrument_name, start_timestamp >>> thread = api.public_get_tradingview_chart_data_get(instrument_name, start_timestamp, end_timestamp, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param int start_timestamp: The earliest timestamp to return result for (required) :param int end_timestamp: The most recent timestamp to return result for (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_tradingview_chart_data_get_with_http_info(instrument_name, start_timestamp, end_timestamp, **kwargs) # noqa: E501 - else: - (data) = self.public_get_tradingview_chart_data_get_with_http_info(instrument_name, start_timestamp, end_timestamp, **kwargs) # noqa: E501 - return data + return self.public_get_tradingview_chart_data_get_with_http_info(instrument_name, start_timestamp, end_timestamp, **kwargs) # noqa: E501 def public_get_tradingview_chart_data_get_with_http_info(self, instrument_name, start_timestamp, end_timestamp, **kwargs): # noqa: E501 """Publicly available market data used to generate a TradingView candle chart. # noqa: E501 @@ -2047,11 +2278,20 @@ def public_get_tradingview_chart_data_get_with_http_info(self, instrument_name, >>> thread = api.public_get_tradingview_chart_data_get_with_http_info(instrument_name, start_timestamp, end_timestamp, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param int start_timestamp: The earliest timestamp to return result for (required) :param int end_timestamp: The most recent timestamp to return result for (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -2134,18 +2374,21 @@ def public_test_get(self, **kwargs): # noqa: E501 >>> thread = api.public_test_get(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str expected_result: The value \"exception\" will trigger an error response. This may be useful for testing wrapper libraries. + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_test_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.public_test_get_with_http_info(**kwargs) # noqa: E501 - return data + return self.public_test_get_with_http_info(**kwargs) # noqa: E501 def public_test_get_with_http_info(self, **kwargs): # noqa: E501 """Tests the connection to the API server, and returns its version. You can use this to make sure the API is reachable, and matches the expected version. # noqa: E501 @@ -2155,9 +2398,18 @@ def public_test_get_with_http_info(self, **kwargs): # noqa: E501 >>> thread = api.public_test_get_with_http_info(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str expected_result: The value \"exception\" will trigger an error response. This may be useful for testing wrapper libraries. - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -2224,18 +2476,21 @@ def public_ticker_get(self, instrument_name, **kwargs): # noqa: E501 >>> thread = api.public_ticker_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_ticker_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.public_ticker_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.public_ticker_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def public_ticker_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Get ticker for an instrument. # noqa: E501 @@ -2245,9 +2500,18 @@ def public_ticker_get_with_http_info(self, instrument_name, **kwargs): # noqa: >>> thread = api.public_ticker_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -2318,20 +2582,23 @@ def public_validate_field_get(self, field, value, **kwargs): # noqa: E501 >>> thread = api.public_validate_field_get(field, value, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str field: Name of the field to be validated, examples: postal_code, date_of_birth (required) :param str value: Value to be checked (required) :param str value2: Additional value to be compared with + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_validate_field_get_with_http_info(field, value, **kwargs) # noqa: E501 - else: - (data) = self.public_validate_field_get_with_http_info(field, value, **kwargs) # noqa: E501 - return data + return self.public_validate_field_get_with_http_info(field, value, **kwargs) # noqa: E501 def public_validate_field_get_with_http_info(self, field, value, **kwargs): # noqa: E501 """Method used to introduce the client software connected to Deribit platform over websocket. Provided data may have an impact on the maintained connection and will be collected for internal statistical purposes. In response, Deribit will also introduce itself. # noqa: E501 @@ -2341,11 +2608,20 @@ def public_validate_field_get_with_http_info(self, field, value, **kwargs): # n >>> thread = api.public_validate_field_get_with_http_info(field, value, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str field: Name of the field to be validated, examples: postal_code, date_of_birth (required) :param str value: Value to be checked (required) :param str value2: Additional value to be compared with - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ diff --git a/python/openapi_client/api/supporting_api.py b/python/openapi_client/api/supporting_api.py index b67ca00..43f8775 100644 --- a/python/openapi_client/api/supporting_api.py +++ b/python/openapi_client/api/supporting_api.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ @@ -44,17 +44,20 @@ def public_get_time_get(self, **kwargs): # noqa: E501 >>> thread = api.public_get_time_get(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_get_time_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.public_get_time_get_with_http_info(**kwargs) # noqa: E501 - return data + return self.public_get_time_get_with_http_info(**kwargs) # noqa: E501 def public_get_time_get_with_http_info(self, **kwargs): # noqa: E501 """Retrieves the current time (in milliseconds). This API endpoint can be used to check the clock skew between your software and Deribit's systems. # noqa: E501 @@ -64,8 +67,17 @@ def public_get_time_get_with_http_info(self, **kwargs): # noqa: E501 >>> thread = api.public_get_time_get_with_http_info(async_req=True) >>> result = thread.get() - :param async_req bool - :return: object + :param async_req bool: execute request asynchronously + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -130,18 +142,21 @@ def public_test_get(self, **kwargs): # noqa: E501 >>> thread = api.public_test_get(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str expected_result: The value \"exception\" will trigger an error response. This may be useful for testing wrapper libraries. + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.public_test_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.public_test_get_with_http_info(**kwargs) # noqa: E501 - return data + return self.public_test_get_with_http_info(**kwargs) # noqa: E501 def public_test_get_with_http_info(self, **kwargs): # noqa: E501 """Tests the connection to the API server, and returns its version. You can use this to make sure the API is reachable, and matches the expected version. # noqa: E501 @@ -151,9 +166,18 @@ def public_test_get_with_http_info(self, **kwargs): # noqa: E501 >>> thread = api.public_test_get_with_http_info(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str expected_result: The value \"exception\" will trigger an error response. This may be useful for testing wrapper libraries. - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ diff --git a/python/openapi_client/api/trading_api.py b/python/openapi_client/api/trading_api.py index f4945ff..728daf8 100644 --- a/python/openapi_client/api/trading_api.py +++ b/python/openapi_client/api/trading_api.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ @@ -44,7 +44,7 @@ def private_buy_get(self, instrument_name, amount, **kwargs): # noqa: E501 >>> thread = api.private_buy_get(instrument_name, amount, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param float amount: It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH (required) :param str type: The order type, default: `\"limit\"` @@ -57,16 +57,19 @@ def private_buy_get(self, instrument_name, amount, **kwargs): # noqa: E501 :param float stop_price: Stop price, required for stop limit orders (Only for stop orders) :param str trigger: Defines trigger type, required for `\"stop_limit\"` order type :param str advanced: Advanced option order type. (Only for options) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_buy_get_with_http_info(instrument_name, amount, **kwargs) # noqa: E501 - else: - (data) = self.private_buy_get_with_http_info(instrument_name, amount, **kwargs) # noqa: E501 - return data + return self.private_buy_get_with_http_info(instrument_name, amount, **kwargs) # noqa: E501 def private_buy_get_with_http_info(self, instrument_name, amount, **kwargs): # noqa: E501 """Places a buy order for an instrument. # noqa: E501 @@ -76,7 +79,7 @@ def private_buy_get_with_http_info(self, instrument_name, amount, **kwargs): # >>> thread = api.private_buy_get_with_http_info(instrument_name, amount, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param float amount: It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH (required) :param str type: The order type, default: `\"limit\"` @@ -89,7 +92,16 @@ def private_buy_get_with_http_info(self, instrument_name, amount, **kwargs): # :param float stop_price: Stop price, required for stop limit orders (Only for stop orders) :param str trigger: Defines trigger type, required for `\"stop_limit\"` order type :param str advanced: Advanced option order type. (Only for options) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -186,20 +198,23 @@ def private_cancel_all_by_currency_get(self, currency, **kwargs): # noqa: E501 >>> thread = api.private_cancel_all_by_currency_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered :param str type: Order type - limit, stop or all, default - `all` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_cancel_all_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.private_cancel_all_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.private_cancel_all_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 def private_cancel_all_by_currency_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Cancels all orders by currency, optionally filtered by instrument kind and/or order type. # noqa: E501 @@ -209,11 +224,20 @@ def private_cancel_all_by_currency_get_with_http_info(self, currency, **kwargs): >>> thread = api.private_cancel_all_by_currency_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered :param str type: Order type - limit, stop or all, default - `all` - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -288,19 +312,22 @@ def private_cancel_all_by_instrument_get(self, instrument_name, **kwargs): # no >>> thread = api.private_cancel_all_by_instrument_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param str type: Order type - limit, stop or all, default - `all` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_cancel_all_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.private_cancel_all_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.private_cancel_all_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def private_cancel_all_by_instrument_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Cancels all orders by instrument, optionally filtered by order type. # noqa: E501 @@ -310,10 +337,19 @@ def private_cancel_all_by_instrument_get_with_http_info(self, instrument_name, * >>> thread = api.private_cancel_all_by_instrument_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param str type: Order type - limit, stop or all, default - `all` - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -386,17 +422,20 @@ def private_cancel_all_get(self, **kwargs): # noqa: E501 >>> thread = api.private_cancel_all_get(async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_cancel_all_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.private_cancel_all_get_with_http_info(**kwargs) # noqa: E501 - return data + return self.private_cancel_all_get_with_http_info(**kwargs) # noqa: E501 def private_cancel_all_get_with_http_info(self, **kwargs): # noqa: E501 """This method cancels all users orders and stop orders within all currencies and instrument kinds. # noqa: E501 @@ -406,8 +445,17 @@ def private_cancel_all_get_with_http_info(self, **kwargs): # noqa: E501 >>> thread = api.private_cancel_all_get_with_http_info(async_req=True) >>> result = thread.get() - :param async_req bool - :return: object + :param async_req bool: execute request asynchronously + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -472,18 +520,21 @@ def private_cancel_get(self, order_id, **kwargs): # noqa: E501 >>> thread = api.private_cancel_get(order_id, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str order_id: The order id (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_cancel_get_with_http_info(order_id, **kwargs) # noqa: E501 - else: - (data) = self.private_cancel_get_with_http_info(order_id, **kwargs) # noqa: E501 - return data + return self.private_cancel_get_with_http_info(order_id, **kwargs) # noqa: E501 def private_cancel_get_with_http_info(self, order_id, **kwargs): # noqa: E501 """Cancel an order, specified by order id # noqa: E501 @@ -493,9 +544,18 @@ def private_cancel_get_with_http_info(self, order_id, **kwargs): # noqa: E501 >>> thread = api.private_cancel_get_with_http_info(order_id, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str order_id: The order id (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -566,20 +626,23 @@ def private_close_position_get(self, instrument_name, type, **kwargs): # noqa: >>> thread = api.private_close_position_get(instrument_name, type, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param str type: The order type (required) :param float price: Optional price for limit order. + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_close_position_get_with_http_info(instrument_name, type, **kwargs) # noqa: E501 - else: - (data) = self.private_close_position_get_with_http_info(instrument_name, type, **kwargs) # noqa: E501 - return data + return self.private_close_position_get_with_http_info(instrument_name, type, **kwargs) # noqa: E501 def private_close_position_get_with_http_info(self, instrument_name, type, **kwargs): # noqa: E501 """Makes closing position reduce only order . # noqa: E501 @@ -589,11 +652,20 @@ def private_close_position_get_with_http_info(self, instrument_name, type, **kwa >>> thread = api.private_close_position_get_with_http_info(instrument_name, type, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param str type: The order type (required) :param float price: Optional price for limit order. - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -672,23 +744,26 @@ def private_edit_get(self, order_id, amount, price, **kwargs): # noqa: E501 >>> thread = api.private_edit_get(order_id, amount, price, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str order_id: The order id (required) :param float amount: It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH (required) :param float price:

The order price in base currency.

When editing an option order with advanced=usd, the field price should be the option price value in USD.

When editing an option order with advanced=implv, the field price should be a value of implied volatility in percentages. For example, price=100, means implied volatility of 100%

(required) :param bool post_only:

If true, the order is considered post-only. If the new price would cause the order to be filled immediately (as taker), the price will be changed to be just below the bid.

Only valid in combination with time_in_force=`\"good_til_cancelled\"`

:param str advanced: Advanced option order type. If you have posted an advanced option order, it is necessary to re-supply this parameter when editing it (Only for options) :param float stop_price: Stop price, required for stop limit orders (Only for stop orders) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_edit_get_with_http_info(order_id, amount, price, **kwargs) # noqa: E501 - else: - (data) = self.private_edit_get_with_http_info(order_id, amount, price, **kwargs) # noqa: E501 - return data + return self.private_edit_get_with_http_info(order_id, amount, price, **kwargs) # noqa: E501 def private_edit_get_with_http_info(self, order_id, amount, price, **kwargs): # noqa: E501 """Change price, amount and/or other properties of an order. # noqa: E501 @@ -698,14 +773,23 @@ def private_edit_get_with_http_info(self, order_id, amount, price, **kwargs): # >>> thread = api.private_edit_get_with_http_info(order_id, amount, price, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str order_id: The order id (required) :param float amount: It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH (required) :param float price:

The order price in base currency.

When editing an option order with advanced=usd, the field price should be the option price value in USD.

When editing an option order with advanced=implv, the field price should be a value of implied volatility in percentages. For example, price=100, means implied volatility of 100%

(required) :param bool post_only:

If true, the order is considered post-only. If the new price would cause the order to be filled immediately (as taker), the price will be changed to be just below the bid.

Only valid in combination with time_in_force=`\"good_til_cancelled\"`

:param str advanced: Advanced option order type. If you have posted an advanced option order, it is necessary to re-supply this parameter when editing it (Only for options) :param float stop_price: Stop price, required for stop limit orders (Only for stop orders) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -794,20 +878,23 @@ def private_get_margins_get(self, instrument_name, amount, price, **kwargs): # >>> thread = api.private_get_margins_get(instrument_name, amount, price, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param float amount: Amount, integer for future, float for option. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH. (required) :param float price: Price (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_margins_get_with_http_info(instrument_name, amount, price, **kwargs) # noqa: E501 - else: - (data) = self.private_get_margins_get_with_http_info(instrument_name, amount, price, **kwargs) # noqa: E501 - return data + return self.private_get_margins_get_with_http_info(instrument_name, amount, price, **kwargs) # noqa: E501 def private_get_margins_get_with_http_info(self, instrument_name, amount, price, **kwargs): # noqa: E501 """Get margins for given instrument, amount and price. # noqa: E501 @@ -817,11 +904,20 @@ def private_get_margins_get_with_http_info(self, instrument_name, amount, price, >>> thread = api.private_get_margins_get_with_http_info(instrument_name, amount, price, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param float amount: Amount, integer for future, float for option. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH. (required) :param float price: Price (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -904,20 +1000,23 @@ def private_get_open_orders_by_currency_get(self, currency, **kwargs): # noqa: >>> thread = api.private_get_open_orders_by_currency_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered :param str type: Order type, default - `all` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_open_orders_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.private_get_open_orders_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.private_get_open_orders_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 def private_get_open_orders_by_currency_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieves list of user's open orders. # noqa: E501 @@ -927,11 +1026,20 @@ def private_get_open_orders_by_currency_get_with_http_info(self, currency, **kwa >>> thread = api.private_get_open_orders_by_currency_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered :param str type: Order type, default - `all` - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1006,19 +1114,22 @@ def private_get_open_orders_by_instrument_get(self, instrument_name, **kwargs): >>> thread = api.private_get_open_orders_by_instrument_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param str type: Order type, default - `all` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_open_orders_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.private_get_open_orders_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.private_get_open_orders_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def private_get_open_orders_by_instrument_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Retrieves list of user's open orders within given Instrument. # noqa: E501 @@ -1028,10 +1139,19 @@ def private_get_open_orders_by_instrument_get_with_http_info(self, instrument_na >>> thread = api.private_get_open_orders_by_instrument_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param str type: Order type, default - `all` - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1104,23 +1224,26 @@ def private_get_order_history_by_currency_get(self, currency, **kwargs): # noqa >>> thread = api.private_get_order_history_by_currency_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered :param int count: Number of requested items, default - `20` :param int offset: The offset for pagination, default - `0` :param bool include_old: Include in result orders older than 2 days, default - `false` :param bool include_unfilled: Include in result fully unfilled closed orders, default - `false` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_order_history_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.private_get_order_history_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.private_get_order_history_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 def private_get_order_history_by_currency_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieves history of orders that have been partially or fully filled. # noqa: E501 @@ -1130,14 +1253,23 @@ def private_get_order_history_by_currency_get_with_http_info(self, currency, **k >>> thread = api.private_get_order_history_by_currency_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered :param int count: Number of requested items, default - `20` :param int offset: The offset for pagination, default - `0` :param bool include_old: Include in result orders older than 2 days, default - `false` :param bool include_unfilled: Include in result fully unfilled closed orders, default - `false` - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1218,22 +1350,25 @@ def private_get_order_history_by_instrument_get(self, instrument_name, **kwargs) >>> thread = api.private_get_order_history_by_instrument_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param int count: Number of requested items, default - `20` :param int offset: The offset for pagination, default - `0` :param bool include_old: Include in result orders older than 2 days, default - `false` :param bool include_unfilled: Include in result fully unfilled closed orders, default - `false` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_order_history_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.private_get_order_history_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.private_get_order_history_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def private_get_order_history_by_instrument_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Retrieves history of orders that have been partially or fully filled. # noqa: E501 @@ -1243,13 +1378,22 @@ def private_get_order_history_by_instrument_get_with_http_info(self, instrument_ >>> thread = api.private_get_order_history_by_instrument_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param int count: Number of requested items, default - `20` :param int offset: The offset for pagination, default - `0` :param bool include_old: Include in result orders older than 2 days, default - `false` :param bool include_unfilled: Include in result fully unfilled closed orders, default - `false` - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1328,18 +1472,21 @@ def private_get_order_margin_by_ids_get(self, ids, **kwargs): # noqa: E501 >>> thread = api.private_get_order_margin_by_ids_get(ids, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param list[str] ids: Ids of orders (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_order_margin_by_ids_get_with_http_info(ids, **kwargs) # noqa: E501 - else: - (data) = self.private_get_order_margin_by_ids_get_with_http_info(ids, **kwargs) # noqa: E501 - return data + return self.private_get_order_margin_by_ids_get_with_http_info(ids, **kwargs) # noqa: E501 def private_get_order_margin_by_ids_get_with_http_info(self, ids, **kwargs): # noqa: E501 """Retrieves initial margins of given orders # noqa: E501 @@ -1349,9 +1496,18 @@ def private_get_order_margin_by_ids_get_with_http_info(self, ids, **kwargs): # >>> thread = api.private_get_order_margin_by_ids_get_with_http_info(ids, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param list[str] ids: Ids of orders (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1423,18 +1579,21 @@ def private_get_order_state_get(self, order_id, **kwargs): # noqa: E501 >>> thread = api.private_get_order_state_get(order_id, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str order_id: The order id (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_order_state_get_with_http_info(order_id, **kwargs) # noqa: E501 - else: - (data) = self.private_get_order_state_get_with_http_info(order_id, **kwargs) # noqa: E501 - return data + return self.private_get_order_state_get_with_http_info(order_id, **kwargs) # noqa: E501 def private_get_order_state_get_with_http_info(self, order_id, **kwargs): # noqa: E501 """Retrieve the current state of an order. # noqa: E501 @@ -1444,9 +1603,18 @@ def private_get_order_state_get_with_http_info(self, order_id, **kwargs): # noq >>> thread = api.private_get_order_state_get_with_http_info(order_id, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str order_id: The order id (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1517,20 +1685,23 @@ def private_get_settlement_history_by_currency_get(self, currency, **kwargs): # >>> thread = api.private_get_settlement_history_by_currency_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Settlement type :param int count: Number of requested items, default - `20` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_settlement_history_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.private_get_settlement_history_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.private_get_settlement_history_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 def private_get_settlement_history_by_currency_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieves settlement, delivery and bankruptcy events that have affected your account. # noqa: E501 @@ -1540,11 +1711,20 @@ def private_get_settlement_history_by_currency_get_with_http_info(self, currency >>> thread = api.private_get_settlement_history_by_currency_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Settlement type :param int count: Number of requested items, default - `20` - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1619,20 +1799,23 @@ def private_get_settlement_history_by_instrument_get(self, instrument_name, **kw >>> thread = api.private_get_settlement_history_by_instrument_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param str type: Settlement type :param int count: Number of requested items, default - `20` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_settlement_history_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.private_get_settlement_history_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.private_get_settlement_history_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def private_get_settlement_history_by_instrument_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Retrieves public settlement, delivery and bankruptcy events filtered by instrument name # noqa: E501 @@ -1642,11 +1825,20 @@ def private_get_settlement_history_by_instrument_get_with_http_info(self, instru >>> thread = api.private_get_settlement_history_by_instrument_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param str type: Settlement type :param int count: Number of requested items, default - `20` - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1721,7 +1913,7 @@ def private_get_user_trades_by_currency_and_time_get(self, currency, start_times >>> thread = api.private_get_user_trades_by_currency_and_time_get(currency, start_timestamp, end_timestamp, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param int start_timestamp: The earliest timestamp to return result for (required) :param int end_timestamp: The most recent timestamp to return result for (required) @@ -1729,16 +1921,19 @@ def private_get_user_trades_by_currency_and_time_get(self, currency, start_times :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_user_trades_by_currency_and_time_get_with_http_info(currency, start_timestamp, end_timestamp, **kwargs) # noqa: E501 - else: - (data) = self.private_get_user_trades_by_currency_and_time_get_with_http_info(currency, start_timestamp, end_timestamp, **kwargs) # noqa: E501 - return data + return self.private_get_user_trades_by_currency_and_time_get_with_http_info(currency, start_timestamp, end_timestamp, **kwargs) # noqa: E501 def private_get_user_trades_by_currency_and_time_get_with_http_info(self, currency, start_timestamp, end_timestamp, **kwargs): # noqa: E501 """Retrieve the latest user trades that have occurred for instruments in a specific currency symbol and within given time range. # noqa: E501 @@ -1748,7 +1943,7 @@ def private_get_user_trades_by_currency_and_time_get_with_http_info(self, curren >>> thread = api.private_get_user_trades_by_currency_and_time_get_with_http_info(currency, start_timestamp, end_timestamp, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param int start_timestamp: The earliest timestamp to return result for (required) :param int end_timestamp: The most recent timestamp to return result for (required) @@ -1756,7 +1951,16 @@ def private_get_user_trades_by_currency_and_time_get_with_http_info(self, curren :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1847,7 +2051,7 @@ def private_get_user_trades_by_currency_get(self, currency, **kwargs): # noqa: >>> thread = api.private_get_user_trades_by_currency_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered :param str start_id: The ID number of the first trade to be returned @@ -1855,16 +2059,19 @@ def private_get_user_trades_by_currency_get(self, currency, **kwargs): # noqa: :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_user_trades_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.private_get_user_trades_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.private_get_user_trades_by_currency_get_with_http_info(currency, **kwargs) # noqa: E501 def private_get_user_trades_by_currency_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieve the latest user trades that have occurred for instruments in a specific currency symbol. # noqa: E501 @@ -1874,7 +2081,7 @@ def private_get_user_trades_by_currency_get_with_http_info(self, currency, **kwa >>> thread = api.private_get_user_trades_by_currency_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str kind: Instrument kind, if not provided instruments of all kinds are considered :param str start_id: The ID number of the first trade to be returned @@ -1882,7 +2089,16 @@ def private_get_user_trades_by_currency_get_with_http_info(self, currency, **kwa :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1965,23 +2181,26 @@ def private_get_user_trades_by_instrument_and_time_get(self, instrument_name, st >>> thread = api.private_get_user_trades_by_instrument_and_time_get(instrument_name, start_timestamp, end_timestamp, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param int start_timestamp: The earliest timestamp to return result for (required) :param int end_timestamp: The most recent timestamp to return result for (required) :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_user_trades_by_instrument_and_time_get_with_http_info(instrument_name, start_timestamp, end_timestamp, **kwargs) # noqa: E501 - else: - (data) = self.private_get_user_trades_by_instrument_and_time_get_with_http_info(instrument_name, start_timestamp, end_timestamp, **kwargs) # noqa: E501 - return data + return self.private_get_user_trades_by_instrument_and_time_get_with_http_info(instrument_name, start_timestamp, end_timestamp, **kwargs) # noqa: E501 def private_get_user_trades_by_instrument_and_time_get_with_http_info(self, instrument_name, start_timestamp, end_timestamp, **kwargs): # noqa: E501 """Retrieve the latest user trades that have occurred for a specific instrument and within given time range. # noqa: E501 @@ -1991,14 +2210,23 @@ def private_get_user_trades_by_instrument_and_time_get_with_http_info(self, inst >>> thread = api.private_get_user_trades_by_instrument_and_time_get_with_http_info(instrument_name, start_timestamp, end_timestamp, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param int start_timestamp: The earliest timestamp to return result for (required) :param int end_timestamp: The most recent timestamp to return result for (required) :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -2087,23 +2315,26 @@ def private_get_user_trades_by_instrument_get(self, instrument_name, **kwargs): >>> thread = api.private_get_user_trades_by_instrument_get(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param int start_seq: The sequence number of the first trade to be returned :param int end_seq: The sequence number of the last trade to be returned :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_user_trades_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - else: - (data) = self.private_get_user_trades_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 - return data + return self.private_get_user_trades_by_instrument_get_with_http_info(instrument_name, **kwargs) # noqa: E501 def private_get_user_trades_by_instrument_get_with_http_info(self, instrument_name, **kwargs): # noqa: E501 """Retrieve the latest user trades that have occurred for a specific instrument. # noqa: E501 @@ -2113,14 +2344,23 @@ def private_get_user_trades_by_instrument_get_with_http_info(self, instrument_na >>> thread = api.private_get_user_trades_by_instrument_get_with_http_info(instrument_name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param int start_seq: The sequence number of the first trade to be returned :param int end_seq: The sequence number of the last trade to be returned :param int count: Number of requested items, default - `10` :param bool include_old: Include trades older than 7 days, default - `false` :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -2201,19 +2441,22 @@ def private_get_user_trades_by_order_get(self, order_id, **kwargs): # noqa: E50 >>> thread = api.private_get_user_trades_by_order_get(order_id, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str order_id: The order id (required) :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_user_trades_by_order_get_with_http_info(order_id, **kwargs) # noqa: E501 - else: - (data) = self.private_get_user_trades_by_order_get_with_http_info(order_id, **kwargs) # noqa: E501 - return data + return self.private_get_user_trades_by_order_get_with_http_info(order_id, **kwargs) # noqa: E501 def private_get_user_trades_by_order_get_with_http_info(self, order_id, **kwargs): # noqa: E501 """Retrieve the list of user trades that was created for given order # noqa: E501 @@ -2223,10 +2466,19 @@ def private_get_user_trades_by_order_get_with_http_info(self, order_id, **kwargs >>> thread = api.private_get_user_trades_by_order_get_with_http_info(order_id, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str order_id: The order id (required) :param str sorting: Direction of results sorting (`default` value means no sorting, results will be returned in order in which they left the database) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -2299,7 +2551,7 @@ def private_sell_get(self, instrument_name, amount, **kwargs): # noqa: E501 >>> thread = api.private_sell_get(instrument_name, amount, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param float amount: It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH (required) :param str type: The order type, default: `\"limit\"` @@ -2312,16 +2564,19 @@ def private_sell_get(self, instrument_name, amount, **kwargs): # noqa: E501 :param float stop_price: Stop price, required for stop limit orders (Only for stop orders) :param str trigger: Defines trigger type, required for `\"stop_limit\"` order type :param str advanced: Advanced option order type. (Only for options) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_sell_get_with_http_info(instrument_name, amount, **kwargs) # noqa: E501 - else: - (data) = self.private_sell_get_with_http_info(instrument_name, amount, **kwargs) # noqa: E501 - return data + return self.private_sell_get_with_http_info(instrument_name, amount, **kwargs) # noqa: E501 def private_sell_get_with_http_info(self, instrument_name, amount, **kwargs): # noqa: E501 """Places a sell order for an instrument. # noqa: E501 @@ -2331,7 +2586,7 @@ def private_sell_get_with_http_info(self, instrument_name, amount, **kwargs): # >>> thread = api.private_sell_get_with_http_info(instrument_name, amount, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str instrument_name: Instrument name (required) :param float amount: It represents the requested order size. For perpetual and futures the amount is in USD units, for options it is amount of corresponding cryptocurrency contracts, e.g., BTC or ETH (required) :param str type: The order type, default: `\"limit\"` @@ -2344,7 +2599,16 @@ def private_sell_get_with_http_info(self, instrument_name, amount, **kwargs): # :param float stop_price: Stop price, required for stop limit orders (Only for stop orders) :param str trigger: Defines trigger type, required for `\"stop_limit\"` order type :param str advanced: Advanced option order type. (Only for options) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ diff --git a/python/openapi_client/api/wallet_api.py b/python/openapi_client/api/wallet_api.py index f02fc53..5c06cc7 100644 --- a/python/openapi_client/api/wallet_api.py +++ b/python/openapi_client/api/wallet_api.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ @@ -44,22 +44,25 @@ def private_add_to_address_book_get(self, currency, type, address, name, **kwarg >>> thread = api.private_add_to_address_book_get(currency, type, address, name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Address book type (required) :param str address: Address in currency format, it must be in address book (required) :param str name: Name of address book entry (required) :param str tfa: TFA code, required when TFA is enabled for current account + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_add_to_address_book_get_with_http_info(currency, type, address, name, **kwargs) # noqa: E501 - else: - (data) = self.private_add_to_address_book_get_with_http_info(currency, type, address, name, **kwargs) # noqa: E501 - return data + return self.private_add_to_address_book_get_with_http_info(currency, type, address, name, **kwargs) # noqa: E501 def private_add_to_address_book_get_with_http_info(self, currency, type, address, name, **kwargs): # noqa: E501 """Adds new entry to address book of given type # noqa: E501 @@ -69,13 +72,22 @@ def private_add_to_address_book_get_with_http_info(self, currency, type, address >>> thread = api.private_add_to_address_book_get_with_http_info(currency, type, address, name, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Address book type (required) :param str address: Address in currency format, it must be in address book (required) :param str name: Name of address book entry (required) :param str tfa: TFA code, required when TFA is enabled for current account - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -166,20 +178,23 @@ def private_cancel_transfer_by_id_get(self, currency, id, **kwargs): # noqa: E5 >>> thread = api.private_cancel_transfer_by_id_get(currency, id, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param int id: Id of transfer (required) :param str tfa: TFA code, required when TFA is enabled for current account + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_cancel_transfer_by_id_get_with_http_info(currency, id, **kwargs) # noqa: E501 - else: - (data) = self.private_cancel_transfer_by_id_get_with_http_info(currency, id, **kwargs) # noqa: E501 - return data + return self.private_cancel_transfer_by_id_get_with_http_info(currency, id, **kwargs) # noqa: E501 def private_cancel_transfer_by_id_get_with_http_info(self, currency, id, **kwargs): # noqa: E501 """Cancel transfer # noqa: E501 @@ -189,11 +204,20 @@ def private_cancel_transfer_by_id_get_with_http_info(self, currency, id, **kwarg >>> thread = api.private_cancel_transfer_by_id_get_with_http_info(currency, id, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param int id: Id of transfer (required) :param str tfa: TFA code, required when TFA is enabled for current account - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -272,19 +296,22 @@ def private_cancel_withdrawal_get(self, currency, id, **kwargs): # noqa: E501 >>> thread = api.private_cancel_withdrawal_get(currency, id, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param float id: The withdrawal id (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_cancel_withdrawal_get_with_http_info(currency, id, **kwargs) # noqa: E501 - else: - (data) = self.private_cancel_withdrawal_get_with_http_info(currency, id, **kwargs) # noqa: E501 - return data + return self.private_cancel_withdrawal_get_with_http_info(currency, id, **kwargs) # noqa: E501 def private_cancel_withdrawal_get_with_http_info(self, currency, id, **kwargs): # noqa: E501 """Cancels withdrawal request # noqa: E501 @@ -294,10 +321,19 @@ def private_cancel_withdrawal_get_with_http_info(self, currency, id, **kwargs): >>> thread = api.private_cancel_withdrawal_get_with_http_info(currency, id, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param float id: The withdrawal id (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -374,18 +410,21 @@ def private_create_deposit_address_get(self, currency, **kwargs): # noqa: E501 >>> thread = api.private_create_deposit_address_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_create_deposit_address_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.private_create_deposit_address_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.private_create_deposit_address_get_with_http_info(currency, **kwargs) # noqa: E501 def private_create_deposit_address_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Creates deposit address in currency # noqa: E501 @@ -395,9 +434,18 @@ def private_create_deposit_address_get_with_http_info(self, currency, **kwargs): >>> thread = api.private_create_deposit_address_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -468,19 +516,22 @@ def private_get_address_book_get(self, currency, type, **kwargs): # noqa: E501 >>> thread = api.private_get_address_book_get(currency, type, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Address book type (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_address_book_get_with_http_info(currency, type, **kwargs) # noqa: E501 - else: - (data) = self.private_get_address_book_get_with_http_info(currency, type, **kwargs) # noqa: E501 - return data + return self.private_get_address_book_get_with_http_info(currency, type, **kwargs) # noqa: E501 def private_get_address_book_get_with_http_info(self, currency, type, **kwargs): # noqa: E501 """Retrieves address book of given type # noqa: E501 @@ -490,10 +541,19 @@ def private_get_address_book_get_with_http_info(self, currency, type, **kwargs): >>> thread = api.private_get_address_book_get_with_http_info(currency, type, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Address book type (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -570,18 +630,21 @@ def private_get_current_deposit_address_get(self, currency, **kwargs): # noqa: >>> thread = api.private_get_current_deposit_address_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_current_deposit_address_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.private_get_current_deposit_address_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.private_get_current_deposit_address_get_with_http_info(currency, **kwargs) # noqa: E501 def private_get_current_deposit_address_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieve deposit address for currency # noqa: E501 @@ -591,9 +654,18 @@ def private_get_current_deposit_address_get_with_http_info(self, currency, **kwa >>> thread = api.private_get_current_deposit_address_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -664,20 +736,23 @@ def private_get_deposits_get(self, currency, **kwargs): # noqa: E501 >>> thread = api.private_get_deposits_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param int count: Number of requested items, default - `10` :param int offset: The offset for pagination, default - `0` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_deposits_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.private_get_deposits_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.private_get_deposits_get_with_http_info(currency, **kwargs) # noqa: E501 def private_get_deposits_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieve the latest users deposits # noqa: E501 @@ -687,11 +762,20 @@ def private_get_deposits_get_with_http_info(self, currency, **kwargs): # noqa: >>> thread = api.private_get_deposits_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param int count: Number of requested items, default - `10` :param int offset: The offset for pagination, default - `0` - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -766,20 +850,23 @@ def private_get_transfers_get(self, currency, **kwargs): # noqa: E501 >>> thread = api.private_get_transfers_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param int count: Number of requested items, default - `10` :param int offset: The offset for pagination, default - `0` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_transfers_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.private_get_transfers_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.private_get_transfers_get_with_http_info(currency, **kwargs) # noqa: E501 def private_get_transfers_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Adds new entry to address book of given type # noqa: E501 @@ -789,11 +876,20 @@ def private_get_transfers_get_with_http_info(self, currency, **kwargs): # noqa: >>> thread = api.private_get_transfers_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param int count: Number of requested items, default - `10` :param int offset: The offset for pagination, default - `0` - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -868,20 +964,23 @@ def private_get_withdrawals_get(self, currency, **kwargs): # noqa: E501 >>> thread = api.private_get_withdrawals_get(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param int count: Number of requested items, default - `10` :param int offset: The offset for pagination, default - `0` + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_get_withdrawals_get_with_http_info(currency, **kwargs) # noqa: E501 - else: - (data) = self.private_get_withdrawals_get_with_http_info(currency, **kwargs) # noqa: E501 - return data + return self.private_get_withdrawals_get_with_http_info(currency, **kwargs) # noqa: E501 def private_get_withdrawals_get_with_http_info(self, currency, **kwargs): # noqa: E501 """Retrieve the latest users withdrawals # noqa: E501 @@ -891,11 +990,20 @@ def private_get_withdrawals_get_with_http_info(self, currency, **kwargs): # noq >>> thread = api.private_get_withdrawals_get_with_http_info(currency, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param int count: Number of requested items, default - `10` :param int offset: The offset for pagination, default - `0` - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -970,21 +1078,24 @@ def private_remove_from_address_book_get(self, currency, type, address, **kwargs >>> thread = api.private_remove_from_address_book_get(currency, type, address, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Address book type (required) :param str address: Address in currency format, it must be in address book (required) :param str tfa: TFA code, required when TFA is enabled for current account + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_remove_from_address_book_get_with_http_info(currency, type, address, **kwargs) # noqa: E501 - else: - (data) = self.private_remove_from_address_book_get_with_http_info(currency, type, address, **kwargs) # noqa: E501 - return data + return self.private_remove_from_address_book_get_with_http_info(currency, type, address, **kwargs) # noqa: E501 def private_remove_from_address_book_get_with_http_info(self, currency, type, address, **kwargs): # noqa: E501 """Adds new entry to address book of given type # noqa: E501 @@ -994,12 +1105,21 @@ def private_remove_from_address_book_get_with_http_info(self, currency, type, ad >>> thread = api.private_remove_from_address_book_get_with_http_info(currency, type, address, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str type: Address book type (required) :param str address: Address in currency format, it must be in address book (required) :param str tfa: TFA code, required when TFA is enabled for current account - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1084,20 +1204,23 @@ def private_submit_transfer_to_subaccount_get(self, currency, amount, destinatio >>> thread = api.private_submit_transfer_to_subaccount_get(currency, amount, destination, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param float amount: Amount of funds to be transferred (required) :param int destination: Id of destination subaccount (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_submit_transfer_to_subaccount_get_with_http_info(currency, amount, destination, **kwargs) # noqa: E501 - else: - (data) = self.private_submit_transfer_to_subaccount_get_with_http_info(currency, amount, destination, **kwargs) # noqa: E501 - return data + return self.private_submit_transfer_to_subaccount_get_with_http_info(currency, amount, destination, **kwargs) # noqa: E501 def private_submit_transfer_to_subaccount_get_with_http_info(self, currency, amount, destination, **kwargs): # noqa: E501 """Transfer funds to a subaccount. # noqa: E501 @@ -1107,11 +1230,20 @@ def private_submit_transfer_to_subaccount_get_with_http_info(self, currency, amo >>> thread = api.private_submit_transfer_to_subaccount_get_with_http_info(currency, amount, destination, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param float amount: Amount of funds to be transferred (required) :param int destination: Id of destination subaccount (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1194,21 +1326,24 @@ def private_submit_transfer_to_user_get(self, currency, amount, destination, **k >>> thread = api.private_submit_transfer_to_user_get(currency, amount, destination, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param float amount: Amount of funds to be transferred (required) :param str destination: Destination address from address book (required) :param str tfa: TFA code, required when TFA is enabled for current account + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_submit_transfer_to_user_get_with_http_info(currency, amount, destination, **kwargs) # noqa: E501 - else: - (data) = self.private_submit_transfer_to_user_get_with_http_info(currency, amount, destination, **kwargs) # noqa: E501 - return data + return self.private_submit_transfer_to_user_get_with_http_info(currency, amount, destination, **kwargs) # noqa: E501 def private_submit_transfer_to_user_get_with_http_info(self, currency, amount, destination, **kwargs): # noqa: E501 """Transfer funds to a another user. # noqa: E501 @@ -1218,12 +1353,21 @@ def private_submit_transfer_to_user_get_with_http_info(self, currency, amount, d >>> thread = api.private_submit_transfer_to_user_get_with_http_info(currency, amount, destination, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param float amount: Amount of funds to be transferred (required) :param str destination: Destination address from address book (required) :param str tfa: TFA code, required when TFA is enabled for current account - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1308,19 +1452,22 @@ def private_toggle_deposit_address_creation_get(self, currency, state, **kwargs) >>> thread = api.private_toggle_deposit_address_creation_get(currency, state, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param bool state: (required) + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_toggle_deposit_address_creation_get_with_http_info(currency, state, **kwargs) # noqa: E501 - else: - (data) = self.private_toggle_deposit_address_creation_get_with_http_info(currency, state, **kwargs) # noqa: E501 - return data + return self.private_toggle_deposit_address_creation_get_with_http_info(currency, state, **kwargs) # noqa: E501 def private_toggle_deposit_address_creation_get_with_http_info(self, currency, state, **kwargs): # noqa: E501 """Enable or disable deposit address creation # noqa: E501 @@ -1330,10 +1477,19 @@ def private_toggle_deposit_address_creation_get_with_http_info(self, currency, s >>> thread = api.private_toggle_deposit_address_creation_get_with_http_info(currency, state, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param bool state: (required) - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ @@ -1410,22 +1566,25 @@ def private_withdraw_get(self, currency, address, amount, **kwargs): # noqa: E5 >>> thread = api.private_withdraw_get(currency, address, amount, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str address: Address in currency format, it must be in address book (required) :param float amount: Amount of funds to be withdrawn (required) :param str priority: Withdrawal priority, optional for BTC, default: `high` :param str tfa: TFA code, required when TFA is enabled for current account + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. :return: object If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.private_withdraw_get_with_http_info(currency, address, amount, **kwargs) # noqa: E501 - else: - (data) = self.private_withdraw_get_with_http_info(currency, address, amount, **kwargs) # noqa: E501 - return data + return self.private_withdraw_get_with_http_info(currency, address, amount, **kwargs) # noqa: E501 def private_withdraw_get_with_http_info(self, currency, address, amount, **kwargs): # noqa: E501 """Creates a new withdrawal request # noqa: E501 @@ -1435,13 +1594,22 @@ def private_withdraw_get_with_http_info(self, currency, address, amount, **kwarg >>> thread = api.private_withdraw_get_with_http_info(currency, address, amount, async_req=True) >>> result = thread.get() - :param async_req bool + :param async_req bool: execute request asynchronously :param str currency: The currency symbol (required) :param str address: Address in currency format, it must be in address book (required) :param float amount: Amount of funds to be withdrawn (required) :param str priority: Withdrawal priority, optional for BTC, default: `high` :param str tfa: TFA code, required when TFA is enabled for current account - :return: object + :param _return_http_data_only: response data without head status code + and headers + :param _preload_content: if False, the urllib3.HTTPResponse object will + be returned without reading/decoding response + data. Default is True. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: tuple(object, status_code(int), headers(HTTPHeaderDict)) If the method is called asynchronously, returns the request thread. """ diff --git a/python/openapi_client/api_client.py b/python/openapi_client/api_client.py index 82f5469..93542ae 100644 --- a/python/openapi_client/api_client.py +++ b/python/openapi_client/api_client.py @@ -4,7 +4,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/openapi_client/configuration.py b/python/openapi_client/configuration.py index 71b12ac..5f786c6 100644 --- a/python/openapi_client/configuration.py +++ b/python/openapi_client/configuration.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ @@ -27,9 +27,9 @@ def __init__(cls, name, bases, dct): super(TypeWithDefault, cls).__init__(name, bases, dct) cls._default = None - def __call__(cls): + def __call__(cls, **kwargs): if cls._default is None: - cls._default = type.__call__(cls) + cls._default = type.__call__(cls, **kwargs) return copy.copy(cls._default) def set_default(cls, default): @@ -41,69 +41,100 @@ class Configuration(six.with_metaclass(TypeWithDefault, object)): Ref: https://openapi-generator.tech Do not edit the class manually. + + :param host: Base url + :param api_key: Dict to store API key(s) + :param api_key_prefix: Dict to store API prefix (e.g. Bearer) + :param username: Username for HTTP basic authentication + :param password: Password for HTTP basic authentication """ - def __init__(self): - """Constructor""" - # Default Base url - self.host = "https://www.deribit.com/api/v2" - # Temp file folder for downloading files + def __init__(self, host="https://www.deribit.com/api/v2", + api_key={}, api_key_prefix={}, + username="", password=""): + """Constructor + """ + self.host = host + """Default Base url + """ self.temp_folder_path = None - + """Temp file folder for downloading files + """ # Authentication Settings - # dict to store API key(s) - self.api_key = {} - # dict to store API prefix (e.g. Bearer) - self.api_key_prefix = {} - # Username for HTTP basic authentication - self.username = "" - # Password for HTTP basic authentication - self.password = "" - # access token for OAuth/Bearer + self.api_key = api_key + """dict to store API key(s) + """ + self.api_key_prefix = api_key_prefix + """dict to store API prefix (e.g. Bearer) + """ + self.username = username + """Username for HTTP basic authentication + """ + self.password = password + """Password for HTTP basic authentication + """ self.access_token = "" - # Logging Settings + """access token for OAuth/Bearer + """ self.logger = {} + """Logging Settings + """ self.logger["package_logger"] = logging.getLogger("openapi_client") self.logger["urllib3_logger"] = logging.getLogger("urllib3") - # Log format self.logger_format = '%(asctime)s %(levelname)s %(message)s' - # Log stream handler + """Log format + """ self.logger_stream_handler = None - # Log file handler + """Log stream handler + """ self.logger_file_handler = None - # Debug file location + """Log file handler + """ self.logger_file = None - # Debug switch + """Debug file location + """ self.debug = False + """Debug switch + """ - # SSL/TLS verification - # Set this to false to skip verifying SSL certificate when calling API - # from https server. self.verify_ssl = True - # Set this to customize the certificate file to verify the peer. + """SSL/TLS verification + Set this to false to skip verifying SSL certificate when calling API + from https server. + """ self.ssl_ca_cert = None - # client certificate file + """Set this to customize the certificate file to verify the peer. + """ self.cert_file = None - # client key file + """client certificate file + """ self.key_file = None - # Set this to True/False to enable/disable SSL hostname verification. + """client key file + """ self.assert_hostname = None + """Set this to True/False to enable/disable SSL hostname verification. + """ - # urllib3 connection pool's maximum number of connections saved - # per pool. urllib3 uses 1 connection as default value, but this is - # not the best value when you are making a lot of possibly parallel - # requests to the same host, which is often the case here. - # cpu_count * 5 is used as default value to increase performance. self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 + """urllib3 connection pool's maximum number of connections saved + per pool. urllib3 uses 1 connection as default value, but this is + not the best value when you are making a lot of possibly parallel + requests to the same host, which is often the case here. + cpu_count * 5 is used as default value to increase performance. + """ - # Proxy URL self.proxy = None - # Proxy headers + """Proxy URL + """ self.proxy_headers = None - # Safe chars for path_param + """Proxy headers + """ self.safe_chars_for_path_param = '' - # Adding retries to override urllib3 default value 3 + """Safe chars for path_param + """ self.retries = None + """Adding retries to override urllib3 default value 3 + """ @property def logger_file(self): diff --git a/python/openapi_client/exceptions.py b/python/openapi_client/exceptions.py index 52fe579..1ece464 100644 --- a/python/openapi_client/exceptions.py +++ b/python/openapi_client/exceptions.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/openapi_client/models/__init__.py b/python/openapi_client/models/__init__.py index 8d7e5b3..07f2e77 100644 --- a/python/openapi_client/models/__init__.py +++ b/python/openapi_client/models/__init__.py @@ -6,7 +6,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/openapi_client/models/address_book_item.py b/python/openapi_client/models/address_book_item.py index 699f277..12225ea 100644 --- a/python/openapi_client/models/address_book_item.py +++ b/python/openapi_client/models/address_book_item.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/openapi_client/models/book_summary.py b/python/openapi_client/models/book_summary.py index 4c5f644..a39a156 100644 --- a/python/openapi_client/models/book_summary.py +++ b/python/openapi_client/models/book_summary.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/openapi_client/models/currency.py b/python/openapi_client/models/currency.py index ca95a66..3c7f6dd 100644 --- a/python/openapi_client/models/currency.py +++ b/python/openapi_client/models/currency.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/openapi_client/models/currency_portfolio.py b/python/openapi_client/models/currency_portfolio.py index 8c51c4a..e3db877 100644 --- a/python/openapi_client/models/currency_portfolio.py +++ b/python/openapi_client/models/currency_portfolio.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/openapi_client/models/currency_withdrawal_priorities.py b/python/openapi_client/models/currency_withdrawal_priorities.py index 1688267..08ad2e4 100644 --- a/python/openapi_client/models/currency_withdrawal_priorities.py +++ b/python/openapi_client/models/currency_withdrawal_priorities.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/openapi_client/models/deposit.py b/python/openapi_client/models/deposit.py index d46eff0..077cacf 100644 --- a/python/openapi_client/models/deposit.py +++ b/python/openapi_client/models/deposit.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/openapi_client/models/instrument.py b/python/openapi_client/models/instrument.py index b33562e..f0db8f1 100644 --- a/python/openapi_client/models/instrument.py +++ b/python/openapi_client/models/instrument.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/openapi_client/models/key_number_pair.py b/python/openapi_client/models/key_number_pair.py index b376368..abb0fb6 100644 --- a/python/openapi_client/models/key_number_pair.py +++ b/python/openapi_client/models/key_number_pair.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/openapi_client/models/order.py b/python/openapi_client/models/order.py index d46c02d..051e990 100644 --- a/python/openapi_client/models/order.py +++ b/python/openapi_client/models/order.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/openapi_client/models/order_id_initial_margin_pair.py b/python/openapi_client/models/order_id_initial_margin_pair.py index f2aa768..72ab64f 100644 --- a/python/openapi_client/models/order_id_initial_margin_pair.py +++ b/python/openapi_client/models/order_id_initial_margin_pair.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/openapi_client/models/portfolio.py b/python/openapi_client/models/portfolio.py index ffb9d5c..6de352d 100644 --- a/python/openapi_client/models/portfolio.py +++ b/python/openapi_client/models/portfolio.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/openapi_client/models/portfolio_eth.py b/python/openapi_client/models/portfolio_eth.py index 830b2d8..8d6e139 100644 --- a/python/openapi_client/models/portfolio_eth.py +++ b/python/openapi_client/models/portfolio_eth.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/openapi_client/models/position.py b/python/openapi_client/models/position.py index 5c29070..d143c2b 100644 --- a/python/openapi_client/models/position.py +++ b/python/openapi_client/models/position.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/openapi_client/models/public_trade.py b/python/openapi_client/models/public_trade.py index 2992dd7..a9f2d49 100644 --- a/python/openapi_client/models/public_trade.py +++ b/python/openapi_client/models/public_trade.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/openapi_client/models/settlement.py b/python/openapi_client/models/settlement.py index b5d06c9..2705f51 100644 --- a/python/openapi_client/models/settlement.py +++ b/python/openapi_client/models/settlement.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/openapi_client/models/trades_volumes.py b/python/openapi_client/models/trades_volumes.py index 2fe33fd..41c6285 100644 --- a/python/openapi_client/models/trades_volumes.py +++ b/python/openapi_client/models/trades_volumes.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/openapi_client/models/transfer_item.py b/python/openapi_client/models/transfer_item.py index f4abe8c..b8397f8 100644 --- a/python/openapi_client/models/transfer_item.py +++ b/python/openapi_client/models/transfer_item.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/openapi_client/models/types.py b/python/openapi_client/models/types.py index 641b9a0..c02992f 100644 --- a/python/openapi_client/models/types.py +++ b/python/openapi_client/models/types.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/openapi_client/models/user_trade.py b/python/openapi_client/models/user_trade.py index 5b1e7a0..d07fea6 100644 --- a/python/openapi_client/models/user_trade.py +++ b/python/openapi_client/models/user_trade.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/openapi_client/models/withdrawal.py b/python/openapi_client/models/withdrawal.py index e36c150..d28492e 100644 --- a/python/openapi_client/models/withdrawal.py +++ b/python/openapi_client/models/withdrawal.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/openapi_client/rest.py b/python/openapi_client/rest.py index 24e3bde..5ea333d 100644 --- a/python/openapi_client/rest.py +++ b/python/openapi_client/rest.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/python/setup.py b/python/setup.py index 2def14c..3b75f24 100644 --- a/python/setup.py +++ b/python/setup.py @@ -5,7 +5,7 @@ #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # noqa: E501 - OpenAPI spec version: 2.0.0 + The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech """ diff --git a/r/.openapi-generator/VERSION b/r/.openapi-generator/VERSION index afa6365..d96260b 100644 --- a/r/.openapi-generator/VERSION +++ b/r/.openapi-generator/VERSION @@ -1 +1 @@ -4.0.0-SNAPSHOT \ No newline at end of file +4.0.2-SNAPSHOT \ No newline at end of file diff --git a/r/R/account_management_api.R b/r/R/account_management_api.R index 2574d0b..54513cb 100644 --- a/r/R/account_management_api.R +++ b/r/R/account_management_api.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/address_book_item.R b/r/R/address_book_item.R index 7444448..2dae64b 100644 --- a/r/R/address_book_item.R +++ b/r/R/address_book_item.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/api_client.R b/r/R/api_client.R index 996d543..d0233a6 100644 --- a/r/R/api_client.R +++ b/r/R/api_client.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/authentication_api.R b/r/R/authentication_api.R index 49885f4..11a58d3 100644 --- a/r/R/authentication_api.R +++ b/r/R/authentication_api.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/book_summary.R b/r/R/book_summary.R index 49cf977..d37eac7 100644 --- a/r/R/book_summary.R +++ b/r/R/book_summary.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/currency.R b/r/R/currency.R index 0c06d36..6a38ebc 100644 --- a/r/R/currency.R +++ b/r/R/currency.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/currency_portfolio.R b/r/R/currency_portfolio.R index 0fdf0a8..9a3da42 100644 --- a/r/R/currency_portfolio.R +++ b/r/R/currency_portfolio.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/currency_withdrawal_priorities.R b/r/R/currency_withdrawal_priorities.R index 1d1e2c2..6da531b 100644 --- a/r/R/currency_withdrawal_priorities.R +++ b/r/R/currency_withdrawal_priorities.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/deposit.R b/r/R/deposit.R index 465ac04..907dc2d 100644 --- a/r/R/deposit.R +++ b/r/R/deposit.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/instrument.R b/r/R/instrument.R index b2627a9..2e9950a 100644 --- a/r/R/instrument.R +++ b/r/R/instrument.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/internal_api.R b/r/R/internal_api.R index a72e798..0dde135 100644 --- a/r/R/internal_api.R +++ b/r/R/internal_api.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/key_number_pair.R b/r/R/key_number_pair.R index 75fa3cd..5183972 100644 --- a/r/R/key_number_pair.R +++ b/r/R/key_number_pair.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/market_data_api.R b/r/R/market_data_api.R index 4f202dd..822ec95 100644 --- a/r/R/market_data_api.R +++ b/r/R/market_data_api.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/order.R b/r/R/order.R index b31f5cb..757e3e7 100644 --- a/r/R/order.R +++ b/r/R/order.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/order_id_initial_margin_pair.R b/r/R/order_id_initial_margin_pair.R index b2476ba..9779717 100644 --- a/r/R/order_id_initial_margin_pair.R +++ b/r/R/order_id_initial_margin_pair.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/portfolio.R b/r/R/portfolio.R index 26e4835..4ea5f75 100644 --- a/r/R/portfolio.R +++ b/r/R/portfolio.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/portfolio_eth.R b/r/R/portfolio_eth.R index e5f57a7..5da075f 100644 --- a/r/R/portfolio_eth.R +++ b/r/R/portfolio_eth.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/position.R b/r/R/position.R index 7d04207..46e69ad 100644 --- a/r/R/position.R +++ b/r/R/position.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/private_api.R b/r/R/private_api.R index 8bbc48b..9587050 100644 --- a/r/R/private_api.R +++ b/r/R/private_api.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/public_api.R b/r/R/public_api.R index aea9ca4..e6c66eb 100644 --- a/r/R/public_api.R +++ b/r/R/public_api.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/public_trade.R b/r/R/public_trade.R index d1c517a..d61a0fc 100644 --- a/r/R/public_trade.R +++ b/r/R/public_trade.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/settlement.R b/r/R/settlement.R index 8c59d70..af112f3 100644 --- a/r/R/settlement.R +++ b/r/R/settlement.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/supporting_api.R b/r/R/supporting_api.R index 25949a4..7d34630 100644 --- a/r/R/supporting_api.R +++ b/r/R/supporting_api.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/trades_volumes.R b/r/R/trades_volumes.R index d75f7e7..3cc797e 100644 --- a/r/R/trades_volumes.R +++ b/r/R/trades_volumes.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/trading_api.R b/r/R/trading_api.R index b4c1d81..e6eee2e 100644 --- a/r/R/trading_api.R +++ b/r/R/trading_api.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/transfer_item.R b/r/R/transfer_item.R index 8c005d7..4061446 100644 --- a/r/R/transfer_item.R +++ b/r/R/transfer_item.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/types.R b/r/R/types.R index 6727ede..218b032 100644 --- a/r/R/types.R +++ b/r/R/types.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/user_trade.R b/r/R/user_trade.R index c29484b..0158122 100644 --- a/r/R/user_trade.R +++ b/r/R/user_trade.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/wallet_api.R b/r/R/wallet_api.R index e905394..55a97c1 100644 --- a/r/R/wallet_api.R +++ b/r/R/wallet_api.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/r/R/withdrawal.R b/r/R/withdrawal.R index 868d992..c9e33f1 100644 --- a/r/R/withdrawal.R +++ b/r/R/withdrawal.R @@ -2,7 +2,7 @@ # # #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods # -# OpenAPI spec version: 2.0.0 +# The version of the OpenAPI document: 2.0.0 # # Generated by: https://openapi-generator.tech diff --git a/ruby/.openapi-generator/VERSION b/ruby/.openapi-generator/VERSION index afa6365..d96260b 100644 --- a/ruby/.openapi-generator/VERSION +++ b/ruby/.openapi-generator/VERSION @@ -1 +1 @@ -4.0.0-SNAPSHOT \ No newline at end of file +4.0.2-SNAPSHOT \ No newline at end of file diff --git a/ruby/.rubocop.yml b/ruby/.rubocop.yml index 98c7e3c..e9f19c0 100644 --- a/ruby/.rubocop.yml +++ b/ruby/.rubocop.yml @@ -1,7 +1,7 @@ # This file is based on https://github.com/rails/rails/blob/master/.rubocop.yml (MIT license) # Automatically generated by OpenAPI Generator (https://openapi-generator.tech) AllCops: - TargetRubyVersion: 2.2 + TargetRubyVersion: 2.4 # RuboCop has a bunch of cops enabled by default. This setting tells RuboCop # to ignore them, so only the ones explicitly set in this file are enabled. DisabledByDefault: true diff --git a/ruby/README.md b/ruby/README.md index 9e67bcf..2d3053f 100644 --- a/ruby/README.md +++ b/ruby/README.md @@ -402,9 +402,8 @@ require 'openapi_client' # Setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::AccountManagementApi.new @@ -616,5 +615,5 @@ Class | Method | HTTP request | Description ### bearerAuth -- **Type**: HTTP basic authentication +- **Type**: Bearer authentication (Auth. Token) diff --git a/ruby/docs/AccountManagementApi.md b/ruby/docs/AccountManagementApi.md index 27a158e..1c2c3e9 100644 --- a/ruby/docs/AccountManagementApi.md +++ b/ruby/docs/AccountManagementApi.md @@ -36,9 +36,8 @@ Change the user name for a subaccount require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::AccountManagementApi.new @@ -89,9 +88,8 @@ Create a new subaccount require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::AccountManagementApi.new @@ -136,9 +134,8 @@ Disable two factor authentication for a subaccount. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::AccountManagementApi.new @@ -187,9 +184,8 @@ Retrieves user account summary. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::AccountManagementApi.new @@ -242,9 +238,8 @@ Retrieves the language to be used for emails. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::AccountManagementApi.new @@ -289,9 +284,8 @@ Retrieves announcements that have not been marked read by the user. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::AccountManagementApi.new @@ -336,9 +330,8 @@ Retrieve user position. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::AccountManagementApi.new @@ -387,9 +380,8 @@ Retrieve user positions. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::AccountManagementApi.new @@ -442,9 +434,8 @@ Get information about subaccounts require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::AccountManagementApi.new @@ -495,9 +486,8 @@ Marks an announcement as read, so it will not be shown in `get_new_announcements require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::AccountManagementApi.new @@ -546,9 +536,8 @@ Assign an email address to a subaccount. User will receive an email with confirm require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::AccountManagementApi.new @@ -599,9 +588,8 @@ Changes the language to be used for emails. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::AccountManagementApi.new @@ -650,9 +638,8 @@ Set the password for the subaccount require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::AccountManagementApi.new @@ -703,9 +690,8 @@ Enable or disable sending of notifications for the subaccount. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::AccountManagementApi.new @@ -756,9 +742,8 @@ Enable or disable login for a subaccount. If login is disabled and a session for require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::AccountManagementApi.new @@ -809,9 +794,8 @@ Retrieves announcements from the last 30 days. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::AccountManagementApi.new diff --git a/ruby/docs/AuthenticationApi.md b/ruby/docs/AuthenticationApi.md index a5a5ae6..3b5f325 100644 --- a/ruby/docs/AuthenticationApi.md +++ b/ruby/docs/AuthenticationApi.md @@ -23,9 +23,8 @@ Retrieve an Oauth access token, to be used for authentication of 'private' reque require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::AuthenticationApi.new diff --git a/ruby/docs/InternalApi.md b/ruby/docs/InternalApi.md index 1ace672..0103766 100644 --- a/ruby/docs/InternalApi.md +++ b/ruby/docs/InternalApi.md @@ -30,9 +30,8 @@ Adds new entry to address book of given type require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::InternalApi.new @@ -91,9 +90,8 @@ Disables TFA with one time recovery code require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::InternalApi.new @@ -144,9 +142,8 @@ Retrieves address book of given type require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::InternalApi.new @@ -197,9 +194,8 @@ Adds new entry to address book of given type require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::InternalApi.new @@ -256,9 +252,8 @@ Transfer funds to a subaccount. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::InternalApi.new @@ -311,9 +306,8 @@ Transfer funds to a another user. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::InternalApi.new @@ -370,9 +364,8 @@ Enable or disable deposit address creation require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::InternalApi.new @@ -423,9 +416,8 @@ Get information to be displayed in the footer of the website. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::InternalApi.new @@ -470,9 +462,8 @@ Retrives market prices and its implied volatility of options instruments require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::InternalApi.new @@ -521,9 +512,8 @@ Method used to introduce the client software connected to Deribit platform over require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::InternalApi.new diff --git a/ruby/docs/MarketDataApi.md b/ruby/docs/MarketDataApi.md index 961e2d0..a1b8002 100644 --- a/ruby/docs/MarketDataApi.md +++ b/ruby/docs/MarketDataApi.md @@ -38,9 +38,8 @@ Retrieves the summary information such as open interest, 24h volume, etc. for al require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::MarketDataApi.new @@ -93,9 +92,8 @@ Retrieves the summary information such as open interest, 24h volume, etc. for a require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::MarketDataApi.new @@ -144,9 +142,8 @@ Retrieves contract size of provided instrument. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::MarketDataApi.new @@ -195,9 +192,8 @@ Retrieves all cryptocurrencies supported by the API. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::MarketDataApi.new @@ -242,9 +238,8 @@ Retrieve the latest user trades that have occurred for PERPETUAL instruments in require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::MarketDataApi.new @@ -297,9 +292,8 @@ Provides information about historical volatility for given cryptocurrency. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::MarketDataApi.new @@ -348,9 +342,8 @@ Retrieves the current index price for the instruments, for the selected currency require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::MarketDataApi.new @@ -399,9 +392,8 @@ Retrieves available trading instruments. This method can be used to see which in require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::MarketDataApi.new @@ -456,9 +448,8 @@ Retrieves historical settlement, delivery and bankruptcy events coming from all require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::MarketDataApi.new @@ -517,9 +508,8 @@ Retrieves historical public settlement, delivery and bankruptcy events filtered require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::MarketDataApi.new @@ -578,9 +568,8 @@ Retrieve the latest trades that have occurred for instruments in a specific curr require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::MarketDataApi.new @@ -643,9 +632,8 @@ Retrieve the latest trades that have occurred for instruments in a specific curr require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::MarketDataApi.new @@ -708,9 +696,8 @@ Retrieve the latest trades that have occurred for a specific instrument and with require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::MarketDataApi.new @@ -771,9 +758,8 @@ Retrieve the latest trades that have occurred for a specific instrument. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::MarketDataApi.new @@ -834,9 +820,8 @@ Retrieves the order book, along with other market values for a given instrument. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::MarketDataApi.new @@ -889,9 +874,8 @@ Retrieves aggregated 24h trade volumes for different instrument types and curren require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::MarketDataApi.new @@ -936,9 +920,8 @@ Publicly available market data used to generate a TradingView candle chart. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::MarketDataApi.new @@ -991,9 +974,8 @@ Get ticker for an instrument. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::MarketDataApi.new diff --git a/ruby/docs/PrivateApi.md b/ruby/docs/PrivateApi.md index 7c1f72f..37d8e14 100644 --- a/ruby/docs/PrivateApi.md +++ b/ruby/docs/PrivateApi.md @@ -72,9 +72,8 @@ Adds new entry to address book of given type require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -133,9 +132,8 @@ Places a buy order for an instrument. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -208,9 +206,8 @@ Cancels all orders by currency, optionally filtered by instrument kind and/or or require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -265,9 +262,8 @@ Cancels all orders by instrument, optionally filtered by order type. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -320,9 +316,8 @@ This method cancels all users orders and stop orders within all currencies and i require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -367,9 +362,8 @@ Cancel an order, specified by order id require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -418,9 +412,8 @@ Cancel transfer require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -475,9 +468,8 @@ Cancels withdrawal request require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -528,9 +520,8 @@ Change the user name for a subaccount require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -581,9 +572,8 @@ Makes closing position reduce only order . require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -638,9 +628,8 @@ Creates deposit address in currency require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -689,9 +678,8 @@ Create a new subaccount require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -736,9 +724,8 @@ Disable two factor authentication for a subaccount. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -787,9 +774,8 @@ Disables TFA with one time recovery code require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -840,9 +826,8 @@ Change price, amount and/or other properties of an order. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -903,9 +888,8 @@ Retrieves user account summary. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -958,9 +942,8 @@ Retrieves address book of given type require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -1011,9 +994,8 @@ Retrieve deposit address for currency require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -1062,9 +1044,8 @@ Retrieve the latest users deposits require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -1119,9 +1100,8 @@ Retrieves the language to be used for emails. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -1166,9 +1146,8 @@ Get margins for given instrument, amount and price. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -1221,9 +1200,8 @@ Retrieves announcements that have not been marked read by the user. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -1268,9 +1246,8 @@ Retrieves list of user's open orders. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -1325,9 +1302,8 @@ Retrieves list of user's open orders within given Instrument. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -1380,9 +1356,8 @@ Retrieves history of orders that have been partially or fully filled. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -1443,9 +1418,8 @@ Retrieves history of orders that have been partially or fully filled. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -1504,9 +1478,8 @@ Retrieves initial margins of given orders require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -1555,9 +1528,8 @@ Retrieve the current state of an order. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -1606,9 +1578,8 @@ Retrieve user position. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -1657,9 +1628,8 @@ Retrieve user positions. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -1712,9 +1682,8 @@ Retrieves settlement, delivery and bankruptcy events that have affected your acc require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -1769,9 +1738,8 @@ Retrieves public settlement, delivery and bankruptcy events filtered by instrume require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -1826,9 +1794,8 @@ Get information about subaccounts require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -1879,9 +1846,8 @@ Adds new entry to address book of given type require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -1936,9 +1902,8 @@ Retrieve the latest user trades that have occurred for instruments in a specific require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -2001,9 +1966,8 @@ Retrieve the latest user trades that have occurred for instruments in a specific require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -2066,9 +2030,8 @@ Retrieve the latest user trades that have occurred for a specific instrument and require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -2129,9 +2092,8 @@ Retrieve the latest user trades that have occurred for a specific instrument. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -2192,9 +2154,8 @@ Retrieve the list of user trades that was created for given order require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -2247,9 +2208,8 @@ Retrieve the latest users withdrawals require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -2304,9 +2264,8 @@ Adds new entry to address book of given type require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -2363,9 +2322,8 @@ Places a sell order for an instrument. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -2438,9 +2396,8 @@ Marks an announcement as read, so it will not be shown in `get_new_announcements require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -2489,9 +2446,8 @@ Assign an email address to a subaccount. User will receive an email with confirm require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -2542,9 +2498,8 @@ Changes the language to be used for emails. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -2593,9 +2548,8 @@ Set the password for the subaccount require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -2646,9 +2600,8 @@ Transfer funds to a subaccount. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -2701,9 +2654,8 @@ Transfer funds to a another user. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -2760,9 +2712,8 @@ Enable or disable deposit address creation require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -2813,9 +2764,8 @@ Enable or disable sending of notifications for the subaccount. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -2866,9 +2816,8 @@ Enable or disable login for a subaccount. If login is disabled and a session for require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new @@ -2919,9 +2868,8 @@ Creates a new withdrawal request require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PrivateApi.new diff --git a/ruby/docs/PublicApi.md b/ruby/docs/PublicApi.md index 590a714..c671dc8 100644 --- a/ruby/docs/PublicApi.md +++ b/ruby/docs/PublicApi.md @@ -45,9 +45,8 @@ Retrieve an Oauth access token, to be used for authentication of 'private' reque require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PublicApi.new @@ -118,9 +117,8 @@ Retrieves announcements from the last 30 days. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PublicApi.new @@ -165,9 +163,8 @@ Retrieves the summary information such as open interest, 24h volume, etc. for al require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PublicApi.new @@ -220,9 +217,8 @@ Retrieves the summary information such as open interest, 24h volume, etc. for a require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PublicApi.new @@ -271,9 +267,8 @@ Retrieves contract size of provided instrument. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PublicApi.new @@ -322,9 +317,8 @@ Retrieves all cryptocurrencies supported by the API. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PublicApi.new @@ -369,9 +363,8 @@ Retrieve the latest user trades that have occurred for PERPETUAL instruments in require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PublicApi.new @@ -424,9 +417,8 @@ Provides information about historical volatility for given cryptocurrency. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PublicApi.new @@ -475,9 +467,8 @@ Retrieves the current index price for the instruments, for the selected currency require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PublicApi.new @@ -526,9 +517,8 @@ Retrieves available trading instruments. This method can be used to see which in require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PublicApi.new @@ -583,9 +573,8 @@ Retrieves historical settlement, delivery and bankruptcy events coming from all require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PublicApi.new @@ -644,9 +633,8 @@ Retrieves historical public settlement, delivery and bankruptcy events filtered require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PublicApi.new @@ -705,9 +693,8 @@ Retrieve the latest trades that have occurred for instruments in a specific curr require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PublicApi.new @@ -770,9 +757,8 @@ Retrieve the latest trades that have occurred for instruments in a specific curr require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PublicApi.new @@ -835,9 +821,8 @@ Retrieve the latest trades that have occurred for a specific instrument and with require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PublicApi.new @@ -898,9 +883,8 @@ Retrieve the latest trades that have occurred for a specific instrument. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PublicApi.new @@ -961,9 +945,8 @@ Retrieves the order book, along with other market values for a given instrument. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PublicApi.new @@ -1016,9 +999,8 @@ Retrieves the current time (in milliseconds). This API endpoint can be used to c require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PublicApi.new @@ -1063,9 +1045,8 @@ Retrieves aggregated 24h trade volumes for different instrument types and curren require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PublicApi.new @@ -1110,9 +1091,8 @@ Publicly available market data used to generate a TradingView candle chart. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PublicApi.new @@ -1165,9 +1145,8 @@ Tests the connection to the API server, and returns its version. You can use thi require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PublicApi.new @@ -1218,9 +1197,8 @@ Get ticker for an instrument. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PublicApi.new @@ -1269,9 +1247,8 @@ Method used to introduce the client software connected to Deribit platform over require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::PublicApi.new diff --git a/ruby/docs/SupportingApi.md b/ruby/docs/SupportingApi.md index 62b3a13..a3b84a6 100644 --- a/ruby/docs/SupportingApi.md +++ b/ruby/docs/SupportingApi.md @@ -22,9 +22,8 @@ Retrieves the current time (in milliseconds). This API endpoint can be used to c require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::SupportingApi.new @@ -69,9 +68,8 @@ Tests the connection to the API server, and returns its version. You can use thi require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::SupportingApi.new diff --git a/ruby/docs/TradingApi.md b/ruby/docs/TradingApi.md index 9748c67..01618c3 100644 --- a/ruby/docs/TradingApi.md +++ b/ruby/docs/TradingApi.md @@ -42,9 +42,8 @@ Places a buy order for an instrument. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::TradingApi.new @@ -117,9 +116,8 @@ Cancels all orders by currency, optionally filtered by instrument kind and/or or require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::TradingApi.new @@ -174,9 +172,8 @@ Cancels all orders by instrument, optionally filtered by order type. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::TradingApi.new @@ -229,9 +226,8 @@ This method cancels all users orders and stop orders within all currencies and i require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::TradingApi.new @@ -276,9 +272,8 @@ Cancel an order, specified by order id require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::TradingApi.new @@ -327,9 +322,8 @@ Makes closing position reduce only order . require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::TradingApi.new @@ -384,9 +378,8 @@ Change price, amount and/or other properties of an order. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::TradingApi.new @@ -447,9 +440,8 @@ Get margins for given instrument, amount and price. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::TradingApi.new @@ -502,9 +494,8 @@ Retrieves list of user's open orders. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::TradingApi.new @@ -559,9 +550,8 @@ Retrieves list of user's open orders within given Instrument. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::TradingApi.new @@ -614,9 +604,8 @@ Retrieves history of orders that have been partially or fully filled. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::TradingApi.new @@ -677,9 +666,8 @@ Retrieves history of orders that have been partially or fully filled. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::TradingApi.new @@ -738,9 +726,8 @@ Retrieves initial margins of given orders require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::TradingApi.new @@ -789,9 +776,8 @@ Retrieve the current state of an order. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::TradingApi.new @@ -840,9 +826,8 @@ Retrieves settlement, delivery and bankruptcy events that have affected your acc require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::TradingApi.new @@ -897,9 +882,8 @@ Retrieves public settlement, delivery and bankruptcy events filtered by instrume require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::TradingApi.new @@ -954,9 +938,8 @@ Retrieve the latest user trades that have occurred for instruments in a specific require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::TradingApi.new @@ -1019,9 +1002,8 @@ Retrieve the latest user trades that have occurred for instruments in a specific require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::TradingApi.new @@ -1084,9 +1066,8 @@ Retrieve the latest user trades that have occurred for a specific instrument and require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::TradingApi.new @@ -1147,9 +1128,8 @@ Retrieve the latest user trades that have occurred for a specific instrument. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::TradingApi.new @@ -1210,9 +1190,8 @@ Retrieve the list of user trades that was created for given order require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::TradingApi.new @@ -1265,9 +1244,8 @@ Places a sell order for an instrument. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::TradingApi.new diff --git a/ruby/docs/WalletApi.md b/ruby/docs/WalletApi.md index 3f0b9a6..817ffee 100644 --- a/ruby/docs/WalletApi.md +++ b/ruby/docs/WalletApi.md @@ -34,9 +34,8 @@ Adds new entry to address book of given type require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::WalletApi.new @@ -95,9 +94,8 @@ Cancel transfer require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::WalletApi.new @@ -152,9 +150,8 @@ Cancels withdrawal request require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::WalletApi.new @@ -205,9 +202,8 @@ Creates deposit address in currency require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::WalletApi.new @@ -256,9 +252,8 @@ Retrieves address book of given type require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::WalletApi.new @@ -309,9 +304,8 @@ Retrieve deposit address for currency require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::WalletApi.new @@ -360,9 +354,8 @@ Retrieve the latest users deposits require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::WalletApi.new @@ -417,9 +410,8 @@ Adds new entry to address book of given type require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::WalletApi.new @@ -474,9 +466,8 @@ Retrieve the latest users withdrawals require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::WalletApi.new @@ -531,9 +522,8 @@ Adds new entry to address book of given type require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::WalletApi.new @@ -590,9 +580,8 @@ Transfer funds to a subaccount. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::WalletApi.new @@ -645,9 +634,8 @@ Transfer funds to a another user. require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::WalletApi.new @@ -704,9 +692,8 @@ Enable or disable deposit address creation require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::WalletApi.new @@ -757,9 +744,8 @@ Creates a new withdrawal request require 'openapi_client' # setup authorization OpenapiClient.configure do |config| - # Configure HTTP basic authorization: bearerAuth - config.username = 'YOUR USERNAME' - config.password = 'YOUR PASSWORD' + # Configure Bearer authorization (Auth. Token): bearerAuth + config.access_token = 'YOUR_BEARER_TOKEN' end api_instance = OpenapiClient::WalletApi.new diff --git a/ruby/lib/openapi_client.rb b/ruby/lib/openapi_client.rb index b5c1e44..91b08a3 100644 --- a/ruby/lib/openapi_client.rb +++ b/ruby/lib/openapi_client.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/ruby/lib/openapi_client/api/account_management_api.rb b/ruby/lib/openapi_client/api/account_management_api.rb index e6c42b1..cf70339 100644 --- a/ruby/lib/openapi_client/api/account_management_api.rb +++ b/ruby/lib/openapi_client/api/account_management_api.rb @@ -3,14 +3,15 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end require 'uri' +require 'cgi' module OpenapiClient class AccountManagementApi diff --git a/ruby/lib/openapi_client/api/authentication_api.rb b/ruby/lib/openapi_client/api/authentication_api.rb index 94661a4..e2e4a8b 100644 --- a/ruby/lib/openapi_client/api/authentication_api.rb +++ b/ruby/lib/openapi_client/api/authentication_api.rb @@ -3,14 +3,15 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end require 'uri' +require 'cgi' module OpenapiClient class AuthenticationApi diff --git a/ruby/lib/openapi_client/api/internal_api.rb b/ruby/lib/openapi_client/api/internal_api.rb index 145a768..d113fad 100644 --- a/ruby/lib/openapi_client/api/internal_api.rb +++ b/ruby/lib/openapi_client/api/internal_api.rb @@ -3,14 +3,15 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end require 'uri' +require 'cgi' module OpenapiClient class InternalApi diff --git a/ruby/lib/openapi_client/api/market_data_api.rb b/ruby/lib/openapi_client/api/market_data_api.rb index 25f31d0..6f8a637 100644 --- a/ruby/lib/openapi_client/api/market_data_api.rb +++ b/ruby/lib/openapi_client/api/market_data_api.rb @@ -3,14 +3,15 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end require 'uri' +require 'cgi' module OpenapiClient class MarketDataApi diff --git a/ruby/lib/openapi_client/api/private_api.rb b/ruby/lib/openapi_client/api/private_api.rb index 5f394b3..43e781d 100644 --- a/ruby/lib/openapi_client/api/private_api.rb +++ b/ruby/lib/openapi_client/api/private_api.rb @@ -3,14 +3,15 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end require 'uri' +require 'cgi' module OpenapiClient class PrivateApi diff --git a/ruby/lib/openapi_client/api/public_api.rb b/ruby/lib/openapi_client/api/public_api.rb index 73205a8..cffc49d 100644 --- a/ruby/lib/openapi_client/api/public_api.rb +++ b/ruby/lib/openapi_client/api/public_api.rb @@ -3,14 +3,15 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end require 'uri' +require 'cgi' module OpenapiClient class PublicApi diff --git a/ruby/lib/openapi_client/api/supporting_api.rb b/ruby/lib/openapi_client/api/supporting_api.rb index db87811..6250ae0 100644 --- a/ruby/lib/openapi_client/api/supporting_api.rb +++ b/ruby/lib/openapi_client/api/supporting_api.rb @@ -3,14 +3,15 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end require 'uri' +require 'cgi' module OpenapiClient class SupportingApi diff --git a/ruby/lib/openapi_client/api/trading_api.rb b/ruby/lib/openapi_client/api/trading_api.rb index 13f0e2e..1b582ee 100644 --- a/ruby/lib/openapi_client/api/trading_api.rb +++ b/ruby/lib/openapi_client/api/trading_api.rb @@ -3,14 +3,15 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end require 'uri' +require 'cgi' module OpenapiClient class TradingApi diff --git a/ruby/lib/openapi_client/api/wallet_api.rb b/ruby/lib/openapi_client/api/wallet_api.rb index ba46b1e..38d8d32 100644 --- a/ruby/lib/openapi_client/api/wallet_api.rb +++ b/ruby/lib/openapi_client/api/wallet_api.rb @@ -3,14 +3,15 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end require 'uri' +require 'cgi' module OpenapiClient class WalletApi diff --git a/ruby/lib/openapi_client/api_client.rb b/ruby/lib/openapi_client/api_client.rb index 9baf813..78ef132 100644 --- a/ruby/lib/openapi_client/api_client.rb +++ b/ruby/lib/openapi_client/api_client.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/ruby/lib/openapi_client/api_error.rb b/ruby/lib/openapi_client/api_error.rb index 49957d6..68b34c7 100644 --- a/ruby/lib/openapi_client/api_error.rb +++ b/ruby/lib/openapi_client/api_error.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/ruby/lib/openapi_client/configuration.rb b/ruby/lib/openapi_client/configuration.rb index e085465..3f74290 100644 --- a/ruby/lib/openapi_client/configuration.rb +++ b/ruby/lib/openapi_client/configuration.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end @@ -198,10 +198,11 @@ def auth_settings { 'bearerAuth' => { - type: 'basic', + type: 'bearer', in: 'header', + format: 'Auth. Token', key: 'Authorization', - value: basic_auth_token + value: "Bearer #{access_token}" }, } end diff --git a/ruby/lib/openapi_client/models/address_book_item.rb b/ruby/lib/openapi_client/models/address_book_item.rb index e492db6..85f0de8 100644 --- a/ruby/lib/openapi_client/models/address_book_item.rb +++ b/ruby/lib/openapi_client/models/address_book_item.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/ruby/lib/openapi_client/models/book_summary.rb b/ruby/lib/openapi_client/models/book_summary.rb index 70ce798..b042580 100644 --- a/ruby/lib/openapi_client/models/book_summary.rb +++ b/ruby/lib/openapi_client/models/book_summary.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/ruby/lib/openapi_client/models/currency.rb b/ruby/lib/openapi_client/models/currency.rb index f896478..3d53cf9 100644 --- a/ruby/lib/openapi_client/models/currency.rb +++ b/ruby/lib/openapi_client/models/currency.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/ruby/lib/openapi_client/models/currency_portfolio.rb b/ruby/lib/openapi_client/models/currency_portfolio.rb index 3b563e4..c12fdf6 100644 --- a/ruby/lib/openapi_client/models/currency_portfolio.rb +++ b/ruby/lib/openapi_client/models/currency_portfolio.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/ruby/lib/openapi_client/models/currency_withdrawal_priorities.rb b/ruby/lib/openapi_client/models/currency_withdrawal_priorities.rb index 50b0e5a..53c7115 100644 --- a/ruby/lib/openapi_client/models/currency_withdrawal_priorities.rb +++ b/ruby/lib/openapi_client/models/currency_withdrawal_priorities.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/ruby/lib/openapi_client/models/deposit.rb b/ruby/lib/openapi_client/models/deposit.rb index 80fef24..4820917 100644 --- a/ruby/lib/openapi_client/models/deposit.rb +++ b/ruby/lib/openapi_client/models/deposit.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/ruby/lib/openapi_client/models/instrument.rb b/ruby/lib/openapi_client/models/instrument.rb index 7c81f76..a6b5dec 100644 --- a/ruby/lib/openapi_client/models/instrument.rb +++ b/ruby/lib/openapi_client/models/instrument.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/ruby/lib/openapi_client/models/key_number_pair.rb b/ruby/lib/openapi_client/models/key_number_pair.rb index ca02804..bcba0ca 100644 --- a/ruby/lib/openapi_client/models/key_number_pair.rb +++ b/ruby/lib/openapi_client/models/key_number_pair.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/ruby/lib/openapi_client/models/order.rb b/ruby/lib/openapi_client/models/order.rb index bf27647..b16d233 100644 --- a/ruby/lib/openapi_client/models/order.rb +++ b/ruby/lib/openapi_client/models/order.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/ruby/lib/openapi_client/models/order_id_initial_margin_pair.rb b/ruby/lib/openapi_client/models/order_id_initial_margin_pair.rb index 1472cbf..53a8090 100644 --- a/ruby/lib/openapi_client/models/order_id_initial_margin_pair.rb +++ b/ruby/lib/openapi_client/models/order_id_initial_margin_pair.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/ruby/lib/openapi_client/models/portfolio.rb b/ruby/lib/openapi_client/models/portfolio.rb index faaea66..9cfe5cb 100644 --- a/ruby/lib/openapi_client/models/portfolio.rb +++ b/ruby/lib/openapi_client/models/portfolio.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/ruby/lib/openapi_client/models/portfolio_eth.rb b/ruby/lib/openapi_client/models/portfolio_eth.rb index 7503d23..3faed0b 100644 --- a/ruby/lib/openapi_client/models/portfolio_eth.rb +++ b/ruby/lib/openapi_client/models/portfolio_eth.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/ruby/lib/openapi_client/models/position.rb b/ruby/lib/openapi_client/models/position.rb index 17ea948..d397d7b 100644 --- a/ruby/lib/openapi_client/models/position.rb +++ b/ruby/lib/openapi_client/models/position.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/ruby/lib/openapi_client/models/public_trade.rb b/ruby/lib/openapi_client/models/public_trade.rb index 793f692..3e46a6f 100644 --- a/ruby/lib/openapi_client/models/public_trade.rb +++ b/ruby/lib/openapi_client/models/public_trade.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/ruby/lib/openapi_client/models/settlement.rb b/ruby/lib/openapi_client/models/settlement.rb index 0ada4b0..1d9d3b2 100644 --- a/ruby/lib/openapi_client/models/settlement.rb +++ b/ruby/lib/openapi_client/models/settlement.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/ruby/lib/openapi_client/models/trades_volumes.rb b/ruby/lib/openapi_client/models/trades_volumes.rb index b408d97..831076f 100644 --- a/ruby/lib/openapi_client/models/trades_volumes.rb +++ b/ruby/lib/openapi_client/models/trades_volumes.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/ruby/lib/openapi_client/models/transfer_item.rb b/ruby/lib/openapi_client/models/transfer_item.rb index cfc908e..b2bda0c 100644 --- a/ruby/lib/openapi_client/models/transfer_item.rb +++ b/ruby/lib/openapi_client/models/transfer_item.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/ruby/lib/openapi_client/models/types.rb b/ruby/lib/openapi_client/models/types.rb index 7a59352..e10914a 100644 --- a/ruby/lib/openapi_client/models/types.rb +++ b/ruby/lib/openapi_client/models/types.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/ruby/lib/openapi_client/models/user_trade.rb b/ruby/lib/openapi_client/models/user_trade.rb index 1fb74c8..768c531 100644 --- a/ruby/lib/openapi_client/models/user_trade.rb +++ b/ruby/lib/openapi_client/models/user_trade.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/ruby/lib/openapi_client/models/withdrawal.rb b/ruby/lib/openapi_client/models/withdrawal.rb index b271a14..967c2ae 100644 --- a/ruby/lib/openapi_client/models/withdrawal.rb +++ b/ruby/lib/openapi_client/models/withdrawal.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/ruby/lib/openapi_client/version.rb b/ruby/lib/openapi_client/version.rb index 5b723a7..22cc6bb 100644 --- a/ruby/lib/openapi_client/version.rb +++ b/ruby/lib/openapi_client/version.rb @@ -3,10 +3,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/ruby/openapi_client.gemspec b/ruby/openapi_client.gemspec index 5f2661d..339272c 100644 --- a/ruby/openapi_client.gemspec +++ b/ruby/openapi_client.gemspec @@ -5,10 +5,10 @@ ##Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods -OpenAPI spec version: 2.0.0 +The version of the OpenAPI document: 2.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 4.0.0-SNAPSHOT +OpenAPI Generator version: 4.0.2-SNAPSHOT =end diff --git a/scala-akka/.openapi-generator/VERSION b/scala-akka/.openapi-generator/VERSION index afa6365..d96260b 100644 --- a/scala-akka/.openapi-generator/VERSION +++ b/scala-akka/.openapi-generator/VERSION @@ -1 +1 @@ -4.0.0-SNAPSHOT \ No newline at end of file +4.0.2-SNAPSHOT \ No newline at end of file diff --git a/scala-akka/src/main/scala/org/openapitools/client/api/AccountManagementApi.scala b/scala-akka/src/main/scala/org/openapitools/client/api/AccountManagementApi.scala index 60882a9..869a9ab 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/api/AccountManagementApi.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/api/AccountManagementApi.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/api/AuthenticationApi.scala b/scala-akka/src/main/scala/org/openapitools/client/api/AuthenticationApi.scala index 00549f3..ebf7ffa 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/api/AuthenticationApi.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/api/AuthenticationApi.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/api/EnumsSerializers.scala b/scala-akka/src/main/scala/org/openapitools/client/api/EnumsSerializers.scala index 17afb5b..fcdcf1a 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/api/EnumsSerializers.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/api/EnumsSerializers.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/api/InternalApi.scala b/scala-akka/src/main/scala/org/openapitools/client/api/InternalApi.scala index 6e3b81c..bf505da 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/api/InternalApi.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/api/InternalApi.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/api/MarketDataApi.scala b/scala-akka/src/main/scala/org/openapitools/client/api/MarketDataApi.scala index 9303d29..f58f29a 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/api/MarketDataApi.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/api/MarketDataApi.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/api/PrivateApi.scala b/scala-akka/src/main/scala/org/openapitools/client/api/PrivateApi.scala index 04b5873..31c4736 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/api/PrivateApi.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/api/PrivateApi.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/api/PublicApi.scala b/scala-akka/src/main/scala/org/openapitools/client/api/PublicApi.scala index ea8405a..5bb26e8 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/api/PublicApi.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/api/PublicApi.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/api/SupportingApi.scala b/scala-akka/src/main/scala/org/openapitools/client/api/SupportingApi.scala index e107f16..c35423b 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/api/SupportingApi.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/api/SupportingApi.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/api/TradingApi.scala b/scala-akka/src/main/scala/org/openapitools/client/api/TradingApi.scala index 7186b9b..18ce524 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/api/TradingApi.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/api/TradingApi.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/api/WalletApi.scala b/scala-akka/src/main/scala/org/openapitools/client/api/WalletApi.scala index a5e5a62..534aad6 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/api/WalletApi.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/api/WalletApi.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/core/ApiInvoker.scala b/scala-akka/src/main/scala/org/openapitools/client/core/ApiInvoker.scala index 7bf58c1..33ec3ca 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/core/ApiInvoker.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/core/ApiInvoker.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/core/ApiRequest.scala b/scala-akka/src/main/scala/org/openapitools/client/core/ApiRequest.scala index 7a67529..587ad46 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/core/ApiRequest.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/core/ApiRequest.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/core/ApiSettings.scala b/scala-akka/src/main/scala/org/openapitools/client/core/ApiSettings.scala index 7293aac..4361e66 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/core/ApiSettings.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/core/ApiSettings.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/core/requests.scala b/scala-akka/src/main/scala/org/openapitools/client/core/requests.scala index 1b1b374..dd5791f 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/core/requests.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/core/requests.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/model/AddressBookItem.scala b/scala-akka/src/main/scala/org/openapitools/client/model/AddressBookItem.scala index 5c24c8b..d6a9a80 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/model/AddressBookItem.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/model/AddressBookItem.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/model/BookSummary.scala b/scala-akka/src/main/scala/org/openapitools/client/model/BookSummary.scala index fff859b..138a649 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/model/BookSummary.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/model/BookSummary.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/model/Currency.scala b/scala-akka/src/main/scala/org/openapitools/client/model/Currency.scala index 1cc977e..7e0440c 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/model/Currency.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/model/Currency.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/model/CurrencyPortfolio.scala b/scala-akka/src/main/scala/org/openapitools/client/model/CurrencyPortfolio.scala index a049c82..66fcdd7 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/model/CurrencyPortfolio.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/model/CurrencyPortfolio.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/model/CurrencyWithdrawalPriorities.scala b/scala-akka/src/main/scala/org/openapitools/client/model/CurrencyWithdrawalPriorities.scala index bf90f85..5f31c00 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/model/CurrencyWithdrawalPriorities.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/model/CurrencyWithdrawalPriorities.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/model/Deposit.scala b/scala-akka/src/main/scala/org/openapitools/client/model/Deposit.scala index b181267..0f123e5 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/model/Deposit.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/model/Deposit.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/model/Instrument.scala b/scala-akka/src/main/scala/org/openapitools/client/model/Instrument.scala index 8733bd2..cd7a25e 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/model/Instrument.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/model/Instrument.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/model/KeyNumberPair.scala b/scala-akka/src/main/scala/org/openapitools/client/model/KeyNumberPair.scala index 197a863..e0c6585 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/model/KeyNumberPair.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/model/KeyNumberPair.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/model/Order.scala b/scala-akka/src/main/scala/org/openapitools/client/model/Order.scala index 97a36af..4e4917f 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/model/Order.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/model/Order.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/model/OrderIdInitialMarginPair.scala b/scala-akka/src/main/scala/org/openapitools/client/model/OrderIdInitialMarginPair.scala index e47fa47..e08d6b4 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/model/OrderIdInitialMarginPair.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/model/OrderIdInitialMarginPair.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/model/Portfolio.scala b/scala-akka/src/main/scala/org/openapitools/client/model/Portfolio.scala index 5e50c3f..1f184da 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/model/Portfolio.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/model/Portfolio.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/model/PortfolioEth.scala b/scala-akka/src/main/scala/org/openapitools/client/model/PortfolioEth.scala index 9de92a8..392bff0 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/model/PortfolioEth.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/model/PortfolioEth.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/model/Position.scala b/scala-akka/src/main/scala/org/openapitools/client/model/Position.scala index a8f7e68..8ad21d3 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/model/Position.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/model/Position.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/model/PublicTrade.scala b/scala-akka/src/main/scala/org/openapitools/client/model/PublicTrade.scala index a867d91..bd2bc35 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/model/PublicTrade.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/model/PublicTrade.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/model/Settlement.scala b/scala-akka/src/main/scala/org/openapitools/client/model/Settlement.scala index 3adfad4..9416313 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/model/Settlement.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/model/Settlement.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/model/TradesVolumes.scala b/scala-akka/src/main/scala/org/openapitools/client/model/TradesVolumes.scala index 189dc2b..c6c5d74 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/model/TradesVolumes.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/model/TradesVolumes.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/model/TransferItem.scala b/scala-akka/src/main/scala/org/openapitools/client/model/TransferItem.scala index 43325ce..5e3e422 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/model/TransferItem.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/model/TransferItem.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/model/Types.scala b/scala-akka/src/main/scala/org/openapitools/client/model/Types.scala index 6bea609..535043c 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/model/Types.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/model/Types.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/model/UserTrade.scala b/scala-akka/src/main/scala/org/openapitools/client/model/UserTrade.scala index 786dbf9..86f3c8b 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/model/UserTrade.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/model/UserTrade.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/scala-akka/src/main/scala/org/openapitools/client/model/Withdrawal.scala b/scala-akka/src/main/scala/org/openapitools/client/model/Withdrawal.scala index 5d4e5f6..2c3f696 100644 --- a/scala-akka/src/main/scala/org/openapitools/client/model/Withdrawal.scala +++ b/scala-akka/src/main/scala/org/openapitools/client/model/Withdrawal.scala @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It's valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc 'a-z0-9' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d' ' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don't forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here's a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it's modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for 'shell' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/swift4/.openapi-generator/VERSION b/swift4/.openapi-generator/VERSION index afa6365..d96260b 100644 --- a/swift4/.openapi-generator/VERSION +++ b/swift4/.openapi-generator/VERSION @@ -1 +1 @@ -4.0.0-SNAPSHOT \ No newline at end of file +4.0.2-SNAPSHOT \ No newline at end of file diff --git a/typescript-node/.openapi-generator/VERSION b/typescript-node/.openapi-generator/VERSION index afa6365..d96260b 100644 --- a/typescript-node/.openapi-generator/VERSION +++ b/typescript-node/.openapi-generator/VERSION @@ -1 +1 @@ -4.0.0-SNAPSHOT \ No newline at end of file +4.0.2-SNAPSHOT \ No newline at end of file diff --git a/typescript-node/api/accountManagementApi.ts b/typescript-node/api/accountManagementApi.ts index 60c972f..9e43c1d 100644 --- a/typescript-node/api/accountManagementApi.ts +++ b/typescript-node/api/accountManagementApi.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/api/authenticationApi.ts b/typescript-node/api/authenticationApi.ts index 1b6f835..25e1945 100644 --- a/typescript-node/api/authenticationApi.ts +++ b/typescript-node/api/authenticationApi.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/api/internalApi.ts b/typescript-node/api/internalApi.ts index 0ef5c69..6cb1569 100644 --- a/typescript-node/api/internalApi.ts +++ b/typescript-node/api/internalApi.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/api/marketDataApi.ts b/typescript-node/api/marketDataApi.ts index 6b57e93..ce14572 100644 --- a/typescript-node/api/marketDataApi.ts +++ b/typescript-node/api/marketDataApi.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/api/privateApi.ts b/typescript-node/api/privateApi.ts index a813737..58e0b21 100644 --- a/typescript-node/api/privateApi.ts +++ b/typescript-node/api/privateApi.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/api/publicApi.ts b/typescript-node/api/publicApi.ts index f691dcf..ffaab50 100644 --- a/typescript-node/api/publicApi.ts +++ b/typescript-node/api/publicApi.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/api/supportingApi.ts b/typescript-node/api/supportingApi.ts index 4ddcecc..96c4e62 100644 --- a/typescript-node/api/supportingApi.ts +++ b/typescript-node/api/supportingApi.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/api/tradingApi.ts b/typescript-node/api/tradingApi.ts index cdb0963..bad84cb 100644 --- a/typescript-node/api/tradingApi.ts +++ b/typescript-node/api/tradingApi.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/api/walletApi.ts b/typescript-node/api/walletApi.ts index c9f6e8e..00ed525 100644 --- a/typescript-node/api/walletApi.ts +++ b/typescript-node/api/walletApi.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/model/addressBookItem.ts b/typescript-node/model/addressBookItem.ts index cfe9568..84419cf 100644 --- a/typescript-node/model/addressBookItem.ts +++ b/typescript-node/model/addressBookItem.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/model/bookSummary.ts b/typescript-node/model/bookSummary.ts index 78f4821..59d60b9 100644 --- a/typescript-node/model/bookSummary.ts +++ b/typescript-node/model/bookSummary.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/model/currency.ts b/typescript-node/model/currency.ts index 9df86c3..ca87b14 100644 --- a/typescript-node/model/currency.ts +++ b/typescript-node/model/currency.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/model/currencyPortfolio.ts b/typescript-node/model/currencyPortfolio.ts index 143bd68..6df1d86 100644 --- a/typescript-node/model/currencyPortfolio.ts +++ b/typescript-node/model/currencyPortfolio.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/model/currencyWithdrawalPriorities.ts b/typescript-node/model/currencyWithdrawalPriorities.ts index 6664aa4..e4f59b6 100644 --- a/typescript-node/model/currencyWithdrawalPriorities.ts +++ b/typescript-node/model/currencyWithdrawalPriorities.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/model/deposit.ts b/typescript-node/model/deposit.ts index e2848a0..45a49f6 100644 --- a/typescript-node/model/deposit.ts +++ b/typescript-node/model/deposit.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/model/instrument.ts b/typescript-node/model/instrument.ts index de8ca84..390f6f2 100644 --- a/typescript-node/model/instrument.ts +++ b/typescript-node/model/instrument.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/model/keyNumberPair.ts b/typescript-node/model/keyNumberPair.ts index 316113e..c0a040d 100644 --- a/typescript-node/model/keyNumberPair.ts +++ b/typescript-node/model/keyNumberPair.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/model/order.ts b/typescript-node/model/order.ts index c50d5da..1d210e2 100644 --- a/typescript-node/model/order.ts +++ b/typescript-node/model/order.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/model/orderIdInitialMarginPair.ts b/typescript-node/model/orderIdInitialMarginPair.ts index 0fe29ca..b25cba0 100644 --- a/typescript-node/model/orderIdInitialMarginPair.ts +++ b/typescript-node/model/orderIdInitialMarginPair.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/model/portfolio.ts b/typescript-node/model/portfolio.ts index e25c327..8e9bcb2 100644 --- a/typescript-node/model/portfolio.ts +++ b/typescript-node/model/portfolio.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/model/portfolioEth.ts b/typescript-node/model/portfolioEth.ts index faca133..07438f1 100644 --- a/typescript-node/model/portfolioEth.ts +++ b/typescript-node/model/portfolioEth.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/model/position.ts b/typescript-node/model/position.ts index 25c9bff..f9ba804 100644 --- a/typescript-node/model/position.ts +++ b/typescript-node/model/position.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/model/publicTrade.ts b/typescript-node/model/publicTrade.ts index 009e97c..0879d99 100644 --- a/typescript-node/model/publicTrade.ts +++ b/typescript-node/model/publicTrade.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/model/settlement.ts b/typescript-node/model/settlement.ts index 76974a2..a9b05c7 100644 --- a/typescript-node/model/settlement.ts +++ b/typescript-node/model/settlement.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/model/tradesVolumes.ts b/typescript-node/model/tradesVolumes.ts index 16ae831..a56d18b 100644 --- a/typescript-node/model/tradesVolumes.ts +++ b/typescript-node/model/tradesVolumes.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/model/transferItem.ts b/typescript-node/model/transferItem.ts index 180b54c..583cb11 100644 --- a/typescript-node/model/transferItem.ts +++ b/typescript-node/model/transferItem.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/model/types.ts b/typescript-node/model/types.ts index 7102357..7729625 100644 --- a/typescript-node/model/types.ts +++ b/typescript-node/model/types.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/model/userTrade.ts b/typescript-node/model/userTrade.ts index 9bece59..fd41753 100644 --- a/typescript-node/model/userTrade.ts +++ b/typescript-node/model/userTrade.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). diff --git a/typescript-node/model/withdrawal.ts b/typescript-node/model/withdrawal.ts index 257bbda..97b6fce 100644 --- a/typescript-node/model/withdrawal.ts +++ b/typescript-node/model/withdrawal.ts @@ -2,7 +2,7 @@ * Deribit API * #Overview Deribit provides three different interfaces to access the API: * [JSON-RPC over Websocket](#json-rpc) * [JSON-RPC over HTTP](#json-rpc) * [FIX](#fix-api) (Financial Information eXchange) With the API Console you can use and test the JSON-RPC API, both via HTTP and via Websocket. To visit the API console, go to __Account > API tab > API Console tab.__ ##Naming Deribit tradeable assets or instruments use the following system of naming: |Kind|Examples|Template|Comments| |----|--------|--------|--------| |Future|BTC-25MAR16, BTC-5AUG16|BTC-DMMMYY|BTC is currency, DMMMYY is expiration date, D stands for day of month (1 or 2 digits), MMM - month (3 first letters in English), YY stands for year.| |Perpetual|BTC-PERPETUAL ||Perpetual contract for currency BTC.| |Option|BTC-25MAR16-420-C, BTC-5AUG16-580-P|BTC-DMMMYY-STRIKE-K|STRIKE is option strike price in USD. Template K is option kind: C for call options or P for put options.| # JSON-RPC JSON-RPC is a light-weight remote procedure call (RPC) protocol. The [JSON-RPC specification](https://www.jsonrpc.org/specification) defines the data structures that are used for the messages that are exchanged between client and server, as well as the rules around their processing. JSON-RPC uses JSON (RFC 4627) as data format. JSON-RPC is transport agnostic: it does not specify which transport mechanism must be used. The Deribit API supports both Websocket (preferred) and HTTP (with limitations: subscriptions are not supported over HTTP). ## Request messages > An example of a request message: ```json { \"jsonrpc\": \"2.0\", \"id\": 8066, \"method\": \"public/ticker\", \"params\": { \"instrument\": \"BTC-24AUG18-6500-P\" } } ``` According to the JSON-RPC sepcification the requests must be JSON objects with the following fields. |Name|Type|Description| |----|----|-----------| |jsonrpc|string|The version of the JSON-RPC spec: \"2.0\"| |id|integer or string|An identifier of the request. If it is included, then the response will contain the same identifier| |method|string|The method to be invoked| |params|object|The parameters values for the method. The field names must match with the expected parameter names. The parameters that are expected are described in the documentation for the methods, below.| ## Response messages > An example of a response message: ```json { \"jsonrpc\": \"2.0\", \"id\": 5239, \"testnet\": false, \"result\": [ { \"currency\": \"BTC\", \"currencyLong\": \"Bitcoin\", \"minConfirmation\": 2, \"txFee\": 0.0006, \"isActive\": true, \"coinType\": \"BITCOIN\", \"baseAddress\": null } ], \"usIn\": 1535043730126248, \"usOut\": 1535043730126250, \"usDiff\": 2 } ``` The JSON-RPC API always responds with a JSON object with the following fields. |Name|Type|Description| |----|----|-----------| |id|integer|This is the same id that was sent in the request.| |result|any|If successful, the result of the API call. The format for the result is described with each method.| |error|error object|Only present if there was an error invoking the method. The error object is described below.| |testnet|boolean|Indicates whether the API in use is actually the test API. false for production server, true for test server.| |usIn|integer|The timestamp when the requests was received (microseconds since the Unix epoch)| |usOut|integer|The timestamp when the response was sent (microseconds since the Unix epoch)| |usDiff|integer|The number of microseconds that was spent handling the request| > An example of a response with an error: ```json { \"jsonrpc\": \"2.0\", \"id\": 8163, \"error\": { \"code\": 11050, \"message\": \"bad_request\" }, \"testnet\": false, \"usIn\": 1535037392434763, \"usOut\": 1535037392448119, \"usDiff\": 13356 } ``` In case of an error the response message will contain the error field, with as value an object with the following with the following fields: |Name|Type|Description |----|----|-----------| |code|integer|A number that indicates the kind of error.| |message|string|A short description that indicates the kind of error.| |data|any|Additional data about the error. This field may be omitted.| ## Notifications > An example of a notification: ```json { \"jsonrpc\": \"2.0\", \"method\": \"subscription\", \"params\": { \"channel\": \"deribit_price_index.btc_usd\", \"data\": { \"timestamp\": 1535098298227, \"price\": 6521.17, \"index_name\": \"btc_usd\" } } } ``` API users can subscribe to certain types of notifications. This means that they will receive JSON-RPC notification-messages from the server when certain events occur, such as changes to the index price or changes to the order book for a certain instrument. The API methods [public/subscribe](#public-subscribe) and [private/subscribe](#private-subscribe) are used to set up a subscription. Since HTTP does not support the sending of messages from server to client, these methods are only availble when using the Websocket transport mechanism. At the moment of subscription a \"channel\" must be specified. The channel determines the type of events that will be received. See [Subscriptions](#subscriptions) for more details about the channels. In accordance with the JSON-RPC specification, the format of a notification is that of a request message without an id field. The value of the method field will always be \"subscription\". The params field will always be an object with 2 members: channel and data. The value of the channel member is the name of the channel (a string). The value of the data member is an object that contains data that is specific for the channel. ## Authentication > An example of a JSON request with token: ```json { \"id\": 5647, \"method\": \"private/get_subaccounts\", \"params\": { \"access_token\": \"67SVutDoVZSzkUStHSuk51WntMNBJ5mh5DYZhwzpiqDF\" } } ``` The API consists of `public` and `private` methods. The public methods do not require authentication. The private methods use OAuth 2.0 authentication. This means that a valid OAuth access token must be included in the request, which can get achived by calling method [public/auth](#public-auth). When the token was assigned to the user, it should be passed along, with other request parameters, back to the server: |Connection type|Access token placement |----|-----------| |**Websocket**|Inside request JSON parameters, as an `access_token` field| |**HTTP (REST)**|Header `Authorization: bearer ```Token``` ` value| ### Additional authorization method - basic user credentials ! Not recommended - however, it could be useful for quick testing API
Every `private` method could be accessed by providing, inside HTTP `Authorization: Basic XXX` header, values with user `ClientId` and assigned `ClientSecret` (both values can be found on the API page on the Deribit website) encoded with `Base64`: Authorization: Basic BASE64(`ClientId` + `:` + `ClientSecret`) ### Additional authorization method - Deribit signature credentials The Derbit service provides dedicated authorization method, which harness user generated signature to increase security level for passing request data. Generated value is passed inside `Authorization` header, coded as: Authorization: deri-hmac-sha256 id=```ClientId```,ts=```Timestamp```,sig=```Signature```,nonce=```Nonce``` where: |Deribit credential|Description |----|-----------| |*ClientId*|Can be found on the API page on the Deribit website| |*Timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*Signature*|Value for signature calculated as described below | |*Nonce*|Single usage, user generated initialization vector for the server token| The signature is generated by the following formula: Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + RequestData;
RequestData = UPPERCASE(HTTP_METHOD()) + \"\\n\" + URI() + \"\\n\" + RequestBody + \"\\n\";
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 )
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 )
    URI=\"/api/v2/private/get_account_summary?currency=BTC\"
    HttpMethod=GET
    Body=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${HttpMethod}\\n${URI}\\n${Body}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> ea40d5e5e4fae235ab22b61da98121fbf4acdc06db03d632e23c66bcccb90d2c (**WARNING**: Exact value depends on current timestamp and client credentials

    curl -s -X ${HttpMethod} -H \"Authorization: deri-hmac-sha256 id=${ClientId},ts=${Timestamp},nonce=${Nonce},sig=${Signature}\" \"https://www.deribit.com${URI}\"

### Additional authorization method - signature credentials (WebSocket API) When connecting through Websocket, user can request for authorization using ```client_credential``` method, which requires providing following parameters (as a part of JSON request): |JSON parameter|Description |----|-----------| |*grant_type*|Must be **client_signature**| |*client_id*|Can be found on the API page on the Deribit website| |*timestamp*|Time when the request was generated - given as **miliseconds**. It\'s valid for **60 seconds** since generation, after that time any request with an old timestamp will be rejected.| |*signature*|Value for signature calculated as described below | |*nonce*|Single usage, user generated initialization vector for the server token| |*data*|**Optional** field, which contains any user specific value| The signature is generated by the following formula: StringToSign = Timestamp + \"\\n\" + Nonce + \"\\n\" + Data;
Signature = HEX_STRING( HMAC-SHA256( ClientSecret, StringToSign ) );
e.g. (using shell with ```openssl``` tool):     ClientId=AAAAAAAAAAA
    ClientSecret=ABCD
    Timestamp=$( date +%s000 ) # e.g. 1554883365000
    Nonce=$( cat /dev/urandom | tr -dc \'a-z0-9\' | head -c8 ) # e.g. fdbmmz79
    Data=\"\"

    Signature=$( echo -ne \"${Timestamp}\\n${Nonce}\\n${Data}\\n\" | openssl sha256 -r -hmac \"$ClientSecret\" | cut -f1 -d\' \' )

    echo $Signature

    shell output> e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994 (**WARNING**: Exact value depends on current timestamp and client credentials

You can also check the signature value using some online tools like, e.g: [https://codebeautify.org/hmac-generator](https://codebeautify.org/hmac-generator) (but don\'t forget about adding *newline* after each part of the hashed text and remember that you **should use** it only with your **test credentials**). Here\'s a sample JSON request created using the values from the example above: {
  \"jsonrpc\" : \"2.0\",
  \"id\" : 9929,
  \"method\" : \"public/auth\",
  \"params\" :
  {
    \"grant_type\" : \"client_signature\",
    \"client_id\" : \"AAAAAAAAAAA\",
    \"timestamp\": \"1554883365000\",
    \"nonce\": \"fdbmmz79\",
    \"data\": \"\",
    \"signature\" : \"e20c9cd5639d41f8bbc88f4d699c4baf94a4f0ee320e9a116b72743c449eb994\"
  }
}
### Access scope When asking for `access token` user can provide the required access level (called `scope`) which defines what type of functionality he/she wants to use, and whether requests are only going to check for some data or also to update them. Scopes are required and checked for `private` methods, so if you plan to use only `public` information you can stay with values assigned by default. |Scope|Description |----|-----------| |*account:read*|Access to **account** methods - read only data| |*account:read_write*|Access to **account** methods - allows to manage account settings, add subaccounts, etc.| |*trade:read*|Access to **trade** methods - read only data| |*trade:read_write*|Access to **trade** methods - required to create and modify orders| |*wallet:read*|Access to **wallet** methods - read only data| |*wallet:read_write*|Access to **wallet** methods - allows to withdraw, generate new deposit address, etc.| |*wallet:none*, *account:none*, *trade:none*|Blocked access to specified functionality| **NOTICE:** Depending on choosing an authentication method (```grant type```) some scopes could be narrowed by the server. e.g. when ```grant_type = client_credentials``` and ```scope = wallet:read_write``` it\'s modified by the server as ```scope = wallet:read```\" ## JSON-RPC over websocket Websocket is the prefered transport mechanism for the JSON-RPC API, because it is faster and because it can support [subscriptions](#subscriptions) and [cancel on disconnect](#private-enable_cancel_on_disconnect). The code examples that can be found next to each of the methods show how websockets can be used from Python or Javascript/node.js. ## JSON-RPC over HTTP Besides websockets it is also possible to use the API via HTTP. The code examples for \'shell\' show how this can be done using curl. Note that subscriptions and cancel on disconnect are not supported via HTTP. #Methods * - * OpenAPI spec version: 2.0.0 + * The version of the OpenAPI document: 2.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).